希望从可能抓取多个结果的一般xpath返回完整的xpath。
搜索字符串应该是这样的:/myXmlPath @myValue
包含的xml节点可能看起来像这样:
<myXmlPath someAttribute="false" myValue="">
<myXmlPath someAttribute="true" myValue="">
Perl代码如下:
use XML::LibXML;
use XML::XPath::XMLParser;
my $filepath = "c:\temp\myfile.xml";
my $parser = XML::LibXML->new();
$parser->keep_blanks(0);
my $doc = $parser->parse_file($filepath);
@myWarn = ('/myXmlPath/@myValue');
foreach(@myWarn) {
my $nodeset = $doc->findnodes($_);
foreach my $node ($nodeset->get_nodelist) {
my $value = $node->to_literal;
print $_,"n";
print $value," - value n";
print $node," - node n";
}
}
我希望能够评估从xml返回的完整路径值。当我用它来查找xpath中的一般内容时,这段代码工作得很好,但如果我能从节点集结果中获得其他数据,那就更理想了。
就像ikegami说的,我不确定你到底想要什么,所以我对你的问题做出了一种鸟枪式的解释。
use strict;
use warnings;
use XML::LibXML;
use v5.14;
my $doc = XML::LibXML->load_xml(IO => *DATA);
say "Get the full path to the node";
foreach my $node ($doc->findnodes('//myXmlPath/@myValue')) {
say "t".$node->nodePath();
}
say "Get the parent node of the attribute by searching";
foreach my $node ($doc->findnodes('//myXmlPath[./@myValue="banana"]')) {
say "t".$node->nodePath();
my ($someAttribute, $myValue) = map { $node->findvalue("./$_") } qw (@someAttribute @myValue);
say "ttsomeAttribute: $someAttribute";
say "ttmyValue: $myValue";
}
say "Get the parent node programatically";
foreach my $attribute ($doc->findnodes('//myXmlPath/@myValue')) {
my $element = $attribute->parentNode;
say "t".$element->nodePath();
}
__DATA__
<document>
<a>
<b>
<myXmlPath someAttribute="false" myValue="apple" />
</b>
<myXmlPath someAttribute="false" myValue="banana" />
</a>
</document>
将产生:
Get the full path to the node
/document/a/b/myXmlPath/@myValue
/document/a/myXmlPath/@myValue
Get the parent node of the attribute by searching
/document/a/myXmlPath
someAttribute: false
myValue: banana
Get the parent node programatically
/document/a/b/myXmlPath
/document/a/myXmlPath