Nokogiri (Ruby):为每个节点内的特定属性提取标签内容 [英] Nokogiri (Ruby): Extract tag contents for a specific attribute inside each node

查看:44
本文介绍了Nokogiri (Ruby):为每个节点内的特定属性提取标签内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我想为每个 Document 节点提取特定标签的内容,使用如下所示:

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

期望为每 2 个节点提取 id = "ID11" 标签的内容,但没有检索到任何内容.有什么想法吗?

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

推荐答案

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

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

这应该有效:

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

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

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

这篇关于Nokogiri (Ruby):为每个节点内的特定属性提取标签内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆