gpt4 book ai didi

ruby - 通过属性值获取节点

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:13 25 4
gpt4 key购买 nike

我正在尝试通过属性值获取节点。 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_fileid较早设置为分别引用正确的文件和值。我在 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 , 因为它以 / 开头它将从文档的根开始搜索,因为你使用了//您将获得文档中任意位置匹配的所有节点。

您可能想要做的是仅选择上下文节点下的那些节点,即 destination您已经选择的节点。您可以使用 .在表达式的开头:

.//history/history/history

关于ruby - 通过属性值获取节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com