私のコードは、XML ファイル内の関連するテキスト ノードの前にあるパスを「推測」することになっています。この場合の関連性とは、反復する product/person/something タグ内にネストされたテキスト ノードであり、その外部で使用されるテキスト ノードではないことを意味します。
このコード:
@doc, items = Nokogiri.XML(@file), []
path = []
@doc.traverse do |node|
if node.class.to_s == "Nokogiri::XML::Element"
is_path_element = false
node.children.each do |child|
is_path_element = true if child.class.to_s == "Nokogiri::XML::Element"
end
path.push(node.name) if is_path_element == true && !path.include?(node.name)
end
end
final_path = "/"+path.reverse.join("/")
単純な XML ファイルで機能します。たとえば、次のようになります。
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Some XML file title</title>
<description>Some XML file description</description>
<item>
<title>Some product title</title>
<brand>Some product brand</brand>
</item>
<item>
<title>Some product title</title>
<brand>Some product brand</brand>
</item>
</channel>
</rss>
puts final_path # => "/rss/channel/item"
しかし、それがより複雑になった場合、どのようにその課題に取り組むべきでしょうか? たとえば、次のようにします。
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Some XML file title</title>
<description>Some XML file description</description>
<item>
<titles>
<title>Some product title</title>
</titles>
<brands>
<brand>Some product brand</brand>
</brands>
</item>
<item>
<titles>
<title>Some product title</title>
</titles>
<brands>
<brand>Some product brand</brand>
</brands>
</item>
</channel>
</rss>