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

会有一股神秘感。 提交于 2019-12-12 04:25:08

问题


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?


回答1:


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



回答2:


It seemed that xpath used was wrong.

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



回答3:


I managed to get it working with the following code:

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


来源:https://stackoverflow.com/questions/11118411/nokogiri-ruby-extract-tag-contents-for-a-specific-attribute-inside-each-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!