我有下面的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
发布于 2017-06-30 19:13:29
下面(使用|
运算符来组合由三个查询中的任何一个选择的元素集)就可以了:
//hosts/host[./instances/instance/name or ./instances/instance/type]/name/text()
| //hosts/host/instances/instance/name/text()
| //hosts/host/instances/instance/type/text()
发布于 2017-06-30 19:13:14
如果您还想包含hostname
的输出,请尝试以下操作:
//hosts/host//*[self::name or self:: type]/text()
发布于 2017-06-30 23:54:50
您可以使用以下任何一种解决方案来达到您的预期效果-
根目录解决方案-1(完整路径)-您可以跳过:
/root/hosts/host/nametext()|/root/hosts/host/instances/instance/*self::name或self::type
对每个结果分别进行查询的解决方案-2(完整路径):
/root/hosts/host/nametext() |/root/hosts/host/instances/instance/nametext()|/root/hosts/host/instances/instance/typetext()
解决方案-3(节点路径)
//host/nametext()|//instance/*self::name | self::type
解决方案-4(节点路径)
//host/self::name|//instance/self::name | self::type
希望以上内容能有所帮助。
https://stackoverflow.com/questions/44844716
复制相似问题