[英]Get XML-element using XML::LibXML
I need to process xml-file in a different way depending on type element.我需要根据类型元素以不同的方式处理 xml 文件。 I use
findnodes($xpath,$contextNode)
method to find elements that are part of one structure.我使用
findnodes($xpath,$contextNode)
方法来查找属于一个结构的元素。 Elements can have two types <type>A</type>
and <type>B</type>
.元素可以有两种类型
<type>A</type>
和<type>B</type>
。 Is there any way, when I process node with type B to "jump" to element with type A in order to get ID-value?有什么办法,当我处理类型为 B 的节点以“跳转”到类型为 A 的元素以获得 ID 值时?
Basically I need to be able to find out that element with id 2 and type B is in the same structure as element with id 1 and type A. Any ideas how can I jump in structure upwards?基本上我需要能够找出 id 为 2 和类型 B 的元素与 id 为 1 和类型 A 的元素处于相同的结构中。有什么想法可以让我在结构中向上跳转吗?
<structure>
<element>
<def>
<id>1</id>
<type>A</type>
</def>
</element>
<element>
<def>
<id>2</id>
<type>B</type>
</def>
</element>
</structure>
You can use the parent
axis.您可以使用
parent
轴。
my ( $elementB ) = $xpc->findnodes(
"parent::*/element[ def/type='B' ]",
$elementA,
);
Demo on xpather.com [1] xpather.com [1]上的演示
XPath provides the convenient ..
shortcut. XPath 提供方便的
..
快捷方式。
my ( $elementB ) = $xpc->findnodes(
"../element[ def/type='B' ]",
$elementA,
);
Demo on xpather.com [1] xpather.com [1]上的演示
Alternatively, you can use a combination of the preceding-sibling
and following-sibling
axes.或者,您可以组合使用
preceding-sibling
兄弟轴和following-sibling
轴。
my ( $elementB ) = $xpc->findnodes(
" preceding-sibling::*[ def/type='B' ]
| following-sibling::*[ def/type='B' ]
",
$elementA,
);
Demo on xpather.com [1] xpather.com [1]上的演示
Outside of XPath, $node->parentNode
will get the parent node.在 XPath 之外,
$node->parentNode
将获得父节点。 This answer focused on XPath since the OP mentioned findnodes
, and because it's terser and simpler.这个答案集中在 XPath 上,因为 OP 提到
findnodes
,因为它更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.