【发布时间】:2017-07-01 00:01:45
【问题描述】:
我有下面的 xml 文件,我想使用 XPATH 选择主机名、实例名称、实例类型
<root>
<hosts>
<host id="11">
<name>ABC</name>
<instances>
<instance id="11-1">
<name>raj</name>
<type>linux</type>
<date>2017</date>
</instance>
<instance id="11-2">
<name>raj1</name>
<type>linux</type>
<date>2017</date>
</instance>
</instances>
</host>
<host id="12">
<name>XYZ</name>
<instances>
<instance id="12-1">
<name>rahul</name>
<type>solaris</type>
<date>2017</date>
</instance>
</instances>
</host>
</hosts>
</root>
我在 XPATH 下尝试过,它正在选择实例名称和类型,但不确定如何打印主机名以及实例名称和类型。
//hosts/host/instances/instance/*[self::name or self:: type]/text()
它选择以下结果。
raj
linux
raj1
linux
rahul
solaris
但是,我想要如下所示的包含主机名的输出
ABC
raj
linux
raj1
linux
XYZ
rahul
solaris
【问题讨论】:
-
仅供参考,
//在这里非常昂贵——它告诉您的 XPath 引擎它需要在树中的任何位置搜索hosts元素,而不仅仅是在root的正下方。在某些引擎中,有一个用于这种查找的索引(想到 BaseX),但这绝不是一个通用功能。 -
(所以如果效率对您很重要,请考虑使用
/root/hosts而不是//hosts)。