使用 findnodes 的属性查找特殊子节点
Finding a special child node using its atrribute with findnodes
我有一个 XML 文件,说:
<root_node + attribute>
<child_node1 + attribute>
<node1_2 + attribute>
<node1_3>
<node1_4 + attribute>
TEXT COME HERE
</node1_4>
</node1_3>
</node1_2>
</child_node1>
<child_node2 + attribute>
<node2_2 + attribute>
<node2_3>
<node2_4 + attribute>
TEXT COME HERE
</node2_4>
</node2_3>
</node2_2>
</child_node2>
<child_node3 + attribute>
<node3_2 + attribute>
<node3_3>
<node3_4 + attribute>
TEXT COME HERE
</node3_4>
</node3_3>
</node3_2>
</child_node3>
</root_node3>
如您所见,有许多具有不同属性的子节点。为了节省时间,我想使用我事先知道的属性来寻找一个特殊的节点,我想使用它的内部节点。
例如,在上面的XML文件中,我正在寻找child_node2
使用它的属性,然后想将node2_4
的属性保存在一个变量中。
我的问题只是想知道如何直接转到所需的节点(此处child_node2
),然后保存其孙节点的属性。
我希望这能清楚地解释我的问题。
如果你有类似 <child_node myatt="some_value">
的东西,那么 xpath
的语法是:
findnodes('//child_node[@my_att]') # find all with this attribute.
findnodes('//child_node[@my_att="some_value"]') #find this specific instance.
不过,您可以菊花链 findnodes
,以在当前选择条件内找到:
foreach my $element ( $xml -> findnodes('//child_node[@my_att="some_value"]') ) {
$element -> findnodes('//node2_4[@attribute="value"]'); #within this
}
不幸的是,我不能说得更具体,因为您的示例 XML 无效,您也没有准确指出要从中检索哪个 'bit'。
您还可以复合 xpath 元素:
//child_node[@my_att="some_value"]/somechild/someotherchild[@fish_att]
我有一个 XML 文件,说:
<root_node + attribute>
<child_node1 + attribute>
<node1_2 + attribute>
<node1_3>
<node1_4 + attribute>
TEXT COME HERE
</node1_4>
</node1_3>
</node1_2>
</child_node1>
<child_node2 + attribute>
<node2_2 + attribute>
<node2_3>
<node2_4 + attribute>
TEXT COME HERE
</node2_4>
</node2_3>
</node2_2>
</child_node2>
<child_node3 + attribute>
<node3_2 + attribute>
<node3_3>
<node3_4 + attribute>
TEXT COME HERE
</node3_4>
</node3_3>
</node3_2>
</child_node3>
</root_node3>
如您所见,有许多具有不同属性的子节点。为了节省时间,我想使用我事先知道的属性来寻找一个特殊的节点,我想使用它的内部节点。
例如,在上面的XML文件中,我正在寻找child_node2
使用它的属性,然后想将node2_4
的属性保存在一个变量中。
我的问题只是想知道如何直接转到所需的节点(此处child_node2
),然后保存其孙节点的属性。
我希望这能清楚地解释我的问题。
如果你有类似 <child_node myatt="some_value">
的东西,那么 xpath
的语法是:
findnodes('//child_node[@my_att]') # find all with this attribute.
findnodes('//child_node[@my_att="some_value"]') #find this specific instance.
不过,您可以菊花链 findnodes
,以在当前选择条件内找到:
foreach my $element ( $xml -> findnodes('//child_node[@my_att="some_value"]') ) {
$element -> findnodes('//node2_4[@attribute="value"]'); #within this
}
不幸的是,我不能说得更具体,因为您的示例 XML 无效,您也没有准确指出要从中检索哪个 'bit'。
您还可以复合 xpath 元素:
//child_node[@my_att="some_value"]/somechild/someotherchild[@fish_att]