Xml 返回数组中具有相同名称的两个标记的值
我的XML: 输出:Xml 返回数组中具有相同名称的两个标记的值,xml,perl,xml-libxml,Xml,Perl,Xml Libxml,我的XML: 输出: my $xmlDoc = XML::LibXML->new->parse_file($config_file); $Xpath = XML::LibXML::XPathContext->new($xmlDoc); my @item = $Xpath->findnodes('/CONFIG/item'); my $phone = $item[0]->findvalue('/CONFIG/item/phone'); print $phone $
my $xmlDoc = XML::LibXML->new->parse_file($config_file);
$Xpath = XML::LibXML::XPathContext->new($xmlDoc);
my @item = $Xpath->findnodes('/CONFIG/item');
my $phone = $item[0]->findvalue('/CONFIG/item/phone');
print $phone
$phone
包含一个字符串,其中两个数字作为单个实体连接在一起
我甚至尝试过返回数组上下文,它仍然返回一个元素,两个数字连接在一起
您能帮我分别获取这两个电话号码吗?我不清楚您为什么认为必须涉及
XML::LibXML::XPathContext
,因为您显示的XML数据中没有名称空间
你的电话
1234578876543321
返回数组@items
中的单个XML::LibXML::Element
对象,因为只有一个/CONFIG/item
节点。但是你的电话
my @item = $Xpath->findnodes('/CONFIG/item');
忽略该节点的上下文,因为您指定了绝对XPath表达式。它重新扫描文档,查找所有/CONFIG/item/phone
元素,并连接它们的文本值,如您所看到的1234578876543321
我发现find
和findvalue
在这个Perl模块中实现得很差,并且总是依赖findnodes
,这使得事情变得非常简单
my $phone = $item[0]->findvalue('/CONFIG/item/phone');
输出
如果您需要数组中的这些值,那么只需使用map
1234578
876543321
use strict;
use warnings 'all';
use XML::LibXML;
my $dom = XML::LibXML->load_xml(location => 'CONFIG.xml');
print $_->textContent, "\n" for $dom->findnodes('/CONFIG/item/phone');
1234578
876543321
my @phones = map { $_->textContent } $dom->findnodes('/CONFIG/item/phone');