xpath challenge: How to merge multiple results into one result

srlcwrt

New Member
I use Ruby 1.9.3p385 and I use Nokogiri to parse XML files. Not quite sure which xpath version I use, but it does respond to v.1 syntax/functions, and not v.2 syntax.I have this XML file:\[code\]<root_tag> <middle_tag> <item_tag> <headline_1> <tag_1>Product title 1</tag_1> </headline_1> <headline_2> <tag_2>Product attribute 1</tag_2> </headline_2> </item_tag> <item_tag> <headline_1> <tag_1>Product title 2</tag_1> </headline_1> <headline_2> <tag_2>Product attribute 2</tag_2> </headline_2> </item_tag> </middle_tag></root_tag>\[/code\]I want to extract all the products, and for that I am using this code:\[code\]products = xml_file.xpath("/root_tag/middle_tag/item_tag/headline_1|/root_tag/middle_tag/item_tag/headline_2")puts products.size # => 4\[/code\]If you look at the output, using:\[code\]products.each_with_index do |product, i| puts "product #{i}:" puts productend\[/code\]you get this:\[code\]product 0:<headline_1> <tag_1>Product title 1</tag_1></headline_1>product 1:<headline_2> <tag_2>Product attribute 1</tag_2></headline_2>product 2:<headline_1> <tag_1>Product title 2</tag_1></headline_1>product 3:<headline_2> <tag_2>Product attribute 2</tag_2></headline_2>\[/code\]I need my code to join/merge all matches into the same result (so products.size should be 2). The final output should look something like this:\[code\]product 0:<headline_1> <tag_1>Product title 1</tag_1></headline_1><headline_2> <tag_2>Product attribute 1</tag_2></headline_2>product 1:<headline_1> <tag_1>Product title 2</tag_1></headline_1><headline_2> <tag_2>Product attribute 2</tag_2></headline_2>\[/code\]I have looked all over the internet, but all variations, e.g.:\[code\]products = xml_file.xpath("/root_tag/middle_tag/item_tag/*[self::headline_1|self::headline_2]")\[/code\]all seems to output the same result.Am I missing some important point in xpath, or am I overlooking something?
 
Back
Top