Nokogiri (Ruby):提取每个节点内特定属性的标签内容



我有一个具有以下结构的XML。

<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>

我想提取每个文档节点的特定标签的内容,使用如下内容:

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

它应该为每 2 个节点提取 id = "ID11" 的标签的内容,但什么也不检索。有什么想法吗?

你在xpath中有一个小错误,你使用的是/Documents/Document,而你粘贴的XML有点不同。

这应该有效:

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

我最喜欢的方法是使用如下所示的 #css 方法:

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

看来xpath是错误的。

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

我设法让它使用以下代码:

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

最新更新