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

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

    Contents Contents     Contents Contents     

我想使用以下内容为每个Document节点提取特定标记的内容:

 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