通过属性值获取节点

Get node by attribute value

我正在尝试通过属性值获取节点。 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> 的 content/text,它包含属于具有相关 atlas_id 值的 <destination> 节点的 CDATA。

即使 id = val2,我也得到属于 <destination atlas_id = "val1"><history> 的内容。当我编写代码以按属性值查找节点时,我引用了“How to search by attribute value”。

为什么我得到的是错误历史节点的内容?在 IRB 测试后

node = dest_file.xpath("//destination[@atlas_id = #{id}]").first

似乎返回了正确的节点,但下一行得到了错误的内容。问题可能很小或很愚蠢,但我无法发现它。

在您的第二个 XPath 表达式 //history/history/history 中,由于它以 / 开头,它将从 文档的根目录 开始搜索,并且由于您使用// 您将获得 所有 个与文档中任何位置匹配的节点。

您可能想要做的是 select 只有上下文节点下的那些节点,即您已经 select 编辑的 destination 节点。为此,您可以在表达式的开头使用 .

.//history/history/history