xml 将基于同级值的节点与 XPath 匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/912194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:31:53  来源:igfitidea点击:

Matching a node based on a sibling's value with XPath

xmlxpath

提问by Flavius

Having a XML document like this:

有一个像这样的 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<records type="array">
  <record>
    <name>svn</name>
    <record-type>A</record-type>

    <ttl type="integer">86400</ttl>
    <zone-id type="integer">69075</zone-id>
    <aux type="integer">0</aux>
    <id type="integer">xxx</id>
    <active>Y</active>
    <data>xxx.xxx.xxx.xxx</data>

  </record>
  <record>
    <name>domain.tld.</name>
    <record-type>NS</record-type>

    <ttl type="integer">86400</ttl>
    <zone-id type="integer">xxx</zone-id>
    <aux type="integer">0</aux>
    <id type="integer">xxx</id>
    <active>Y</active>
    <data>domain.tld.</data>

  </record>
  <record>
    <name>blog</name>
    <record-type>A</record-type>
    <ttl type="integer">86400</ttl>
    <zone-id type="integer">xxx</zone-id>
    <aux type="integer">0</aux>

    <id type="integer">xxx</id>
    <active>Y</active>
    <data>xxx.xxx.xxx.xxx</data>
  </record>
</records>

How to match all the /records/record/namehaving as sibling /records/record/record-type with the value "A"?

如何将所有/records/record/名称作为兄弟/records/record/record-type 与值“A”匹配?

回答by Flavius

Found it:

找到了:

/records/record/name[../record-type/text() = "A"]

回答by kjhughes

Surprisingly, none of the answers to date on this old question provide the simplestXPath solution.

令人惊讶的是,迄今为止关于这个老问题的答案都没有提供最简单的XPath 解决方案。

This simple XPath

这个简单的 XPath

/records/record[record-type = "A"]/name

selects

选择

<name>svn</name>
<name>blog</name>

as requested.

按照要求。

回答by thomasb

You can also filter a parent element by its children :

您还可以通过其子元素过滤父元素:

/records/record[record-type[text()='A']]/name

/records/record[record-type[text()='A']]/name