检索给定属性的子节点的值

Retrieve value of child node given attribute

我正在尝试检索 Windows Machine 上给定节点的子节点的值。假设我有以下 XML 结构:

<xsd:type name="type1">
    <xsd:example>
      <xsd:description>This is the description of said type1 tag</xsd:description>
    </xsd:example>
</xsd:type>

我想检索 xsd:description 标签之间的值,因为它是具有 name="type1" 属性的 xsd:type 标签的子标签。换句话说,我想检索 "This is the description of said type1 tag"。

在 Mac 上,我可以 运行 下面的命令通过以下命令检索:

xml sel -t -v "//xsd:type[@name=\"type1\"]" -n filePath.xml

然后 returns:"This is the description of said type1 tag" 正如预期的那样。

然而,当我 运行 在我的 Windows 机器上执行完全相同的命令时,命令 returns 是一个空字符串。我不确定 Mac 和 Windows 之间有什么区别,但我似乎无法弄清楚等效的 Windows 命令。

这很可能与未正确定义命名空间有关。

XML Starlet 提供了一个 -N 选项,描述为:

-N <name>=<value>     - predefine namespaces (name without 'xmlns:')
                        ex: xsql=urn:oracle-xsql

将您的命令更改为以下内容:

xml sel -N xsd="http://www.w3.org/2001/XMLSchema" -t -v "//xsd:type[@name=\"type1\"]//xsd:description/text()" -n filePath.xml

备注:

  1. 添加了以下部分以预定义 XPath 表达式的命名空间,以便它在正确的命名空间中寻址元素:

    -N xsd="http://www.w3.org/2001/XMLSchema"

  2. 此外,XPath 表达式已更改为以下内容以更好地满足您的实际需求:

    "//xsd:type[@name=\"type1\"]//xsd:description/text()"

    此表达式匹配任何 xsd:description 元素节点的 text() 节点,该节点是具有 name="type1" 属性的任何 xsd:type 元素节点的后代。