本文介绍了检索给定属性的子节点的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<xsd:description>这是type1标签的描述</xsd:description></xsd:example></xsd:type>

我想检索 xsd:description 标记之间的值,因为它是具有 name="type1" 属性的 xsd:type 标记的子级.换句话说,我想检索这是所述 type1 标签的描述".

在 Mac 上,我可以运行以下命令来检索以下内容:

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

然后按预期返回:这是所述 type1 标签的描述".

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

解决方案

这很可能与没有正确定义命名空间有关.

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

-N =- 预定义命名空间(名称不带 'xmlns:')例如: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() 节点,该节点是任何 xsd:type 元素节点的后代它有一个 name="type1" 属性.

I am trying to retrieve the value of a child node of a given node on a Windows Machine. Suppose I have the following XML structure:

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

I'd like to retrieve the value in between the xsd:description tag given that it is the child of the xsd:type tag with the name="type1" attribute. In other words, I'd like to retrieve "This is the description of said type1 tag".

On a Mac, I'm able to run the below command to retrieve just that with the following:

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

Which then returns: "This is the description of said type1 tag" as expected.

However, when I run the exact same command on my Windows machine, the command returns an empty string. I'm not sure what the differences are between Mac and Windows, but I can't seem to figure out the equivalent Windows command.

解决方案

This is most likely to be related to not properly defining a namespace.

XML Starlet provides a -N option which is described as:

Change your command to the following instead:

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

Notes:

  1. The part below was added to predefine the namespace for the XPath expression, so that it addresses the elements in the correct namespace:

  2. Also the XPath expression was changed to the following to better address your actual requirement:

    This expression matches the text() node of any xsd:description element node that is a descendant of any xsd:type element node which has a name="type1" attribute.

这篇关于检索给定属性的子节点的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:25