简体   繁体   English

XML:使用LibXML查找XML中的特定节点

[英]XML:Find particular node in XML using LibXML

I have an XML file which has only one node called import. 我有一个XML文件,其中只有一个称为import的节点。 I want to find the href attribute of import. 我想找到导入的href属性。 I tried using findnodes(), but that returns a list I would have to search further, so I was hoping there was a way to find a particular node which has only one occurence. 我尝试使用findnodes(),但是返回的列表将使我不得不进一步搜索,因此我希望有一种方法可以找到只发生一次的特定节点。 I tried getChildrenByTagName but that gives the error 我尝试了getChildrenByTagName,但这给出了错误

Can't locate object method "getChildrenByTagName" via package "XML::LibXML::Document"

I also tried grep which gives a similar error 我也尝试了grep,它给出了类似的错误

Can't locate object method "grep" via package "XML::LibXML::Document"

My XML file is: 我的XML文件是:

<?xml version="1.0" encoding="UTF-8"?>
<resource name="data" type="application/dictionary+xml">
<schema>
    <import href="tobefound.xml"/>
</schema>
</resource>

My code so far is 到目前为止,我的代码是

#!/usr/bin/perl
use warnings;
use strict;
use XML::LibXML;

my $name = $ARGV[1];
my $dom = XML::LibXML->load_xml(location => $name);
my @node= $dom->findnodes('//import');
print "List: @node\n";

Please let me know if there is a way to find only one particular node without needing to traverse the whole dom and without having to store it as a list. 请让我知道是否有一种方法可以找到一个特定的节点,而无需遍历整个dom,也不必将其存储为列表。 Thank you. 谢谢。

XML doesn't guarantee uniqueness, so any sort of search will return a list of results. XML不保证唯一性,因此任何类型的搜索都将返回结果列表。 This list might be of length 0 or 1, just like with grep . 就像grep一样,此列表的长度可能为0或1。

But the easy answer is to just grab the first result: 但简单的答案是仅获得第一个结果:

my ($node) = $dom -> findnodes('//import');

failing that - specify in your xpath: 失败-在您的xpath中指定:

my ( $node ) = $dom -> findnodes ( '(//import)[1]' ); 

I'm afraid I don't know if that latter will in fact bail out when 'enough' nodes have been selected though. 恐怕我不知道当选择了“足够”的节点时,后者实际上是否可以纾困。

getChildrenByTagName is a method of Element nodes, not Document nodes. getChildrenByTagName是元素节点而不是文档节点的方法。

my $doc = XML::LibXML->load_xml(location => $name);
my $root_ele = $doc->documentElement();
my ($import_ele) = $root_ele->getChildrenByTagName('import');

You could also use an XPath, though the equivalent XPath would be import (searches children), not //import (searches descendants). 您也可以使用XPath,尽管等效的XPath将是import (搜索子级),而不是//import (搜索后代)。

my $doc = XML::LibXML->load_xml(location => $name);
my ($import_ele) = $doc->findnodes('import');

This returns all the import nodes and keeps the first. 这将返回所有import节点,并保留第一个。 But can tell the search to stop looking after finding the first as follows: 但是可以在找到第一个之后告诉搜索停止查找,如下所示:

my $doc = XML::LibXML->load_xml(location => $name);
my ($import_ele) = $doc->findnodes('import[1]');  # Short for 'import[position()=1]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM