Tedi
Tedi

Reputation: 436

Nokogiri (Ruby): Extract tag contents for a specific attribute inside each node

I have a XML with the following structure

<Root>
   <Batch name="value">
      <Document id="ID1">
         <Tags>
            <Tag id="ID11" name="name11">Contents</Tag>
            <Tag id="ID12" name="name12">Contents</Tag>
         </Tags>
      </Document>

      <Document id="ID2">
         <Tags>
            <Tag id="ID21" name="name21">Contents</Tag>
            <Tag id="ID22" name="name22">Contents</Tag>
         </Tags>
      </Document>
   </Batch>
</Root>

I want to extract the contents of specific tags for each Document node, using something like this:

xml.xpath('//Document/Tags').each do |node|
   puts xml.xpath('//Root/Batch/Document/Tags/Tag[@id="ID11"]').text
end

Which is expected to extract the contents of the tag with id = "ID11" for each 2 nodes, but retrieves nothing. Any ideas?

Upvotes: 0

Views: 419

Answers (3)

Tedi
Tedi

Reputation: 436

I managed to get it working with the following code:

xml.xpath('//Document/Tags').each do |node|
   node.xpath("Tag[@id='ID11']").text
end

Upvotes: 0

Bitterzoet
Bitterzoet

Reputation: 2792

You have a minor error in the xpath, you are using /Documents/Document while the XML you pasted is a bit different.

This should work:

//Root/Batch/Document/Tags/Tag[@id="ID11"]

My favorite way to do this is by using the #css method like this:

xml.css('Tag[@id="ID11"]').each do |node|
  puts node.text
end

Upvotes: 1

guanxiaohua2k6
guanxiaohua2k6

Reputation: 371

It seemed that xpath used was wrong.

'//Root/Batch/Documents/Document/Tags/Tag[@id="ID11"]'
shoud be
'//Root/Batch/Document/Tags/Tag[@id="ID11"]'

Upvotes: 0

Related Questions