我正在尝试通过节点的属性值获取节点。 XML 是由其他人生成的,如下所示:
<destination atlas_id = "val">
<history>
<history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
</history>
</history>
</destination>
<destination atlas_id = "val2">
<history>
<history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
</history>
</history>
</destination>
<destination atlas_id = "val3">
<history>
<history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
<history>
<![CDATA[content]]>
</history>
</history>
</history>
</destination>
我的代码有变量dest_file
和id
之前设置它们分别引用正确的文件和值。我在 IRB 中测试了它们,它们的值是正确的:
node = dest_file.xpath("//destination[@atlas_id = #{id}]").first
doc.text node.xpath("//history/history/history").text unless node.nil?
我想获取第三个嵌套的内容/文本 <history>
,包含属于 <destination>
的 CDATA 的数据相关节点 atlas_id
值(value)。
即使 id = val2
,我得到 <history>
的内容属于<destination atlas_id = "val1">
。当我编写按属性值查找节点的代码时,我引用了“How to search by attribute value”。
为什么我得到了错误历史节点的内容?在 IRB 中测试后
node = dest_file.xpath("//destination[@atlas_id = #{id}]").first
似乎返回了正确的节点,但以下行获取了错误的内容。这个问题可能很小或很愚蠢,但我无法发现它。
最佳答案
在第二个 XPath 表达式 //history/history/history
中,由于它以 /
开头,因此将从文档的根目录开始搜索 em>,并且由于您使用 //
,您将获得文档中任何位置匹配的所有节点。
您可能想要做的是仅选择上下文节点下的那些节点,即您已选择的destination
节点。您可以在表达式的开头使用 .
来实现:
.//history/history/history
关于ruby - 通过属性值获取节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721727/