2015-08-27 64 views
0

尋找從一般xpath返回可能抓取多個結果的完整xpath。Perl XML lib獲取完整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中查找一般事物時,此代碼正常工作,但如果我可以從節點集結果中獲取其他數據,則該代碼會更理想。

+0

我不太明白你想要什麼。你能包括所需的輸出?但首先,你能修正你的例子,因此它是有效的XML嗎? (你提供的有多個根節點和未封閉的元素。) – ikegami

回答

1

就像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 "\t\tsomeAttribute: $someAttribute"; 
    say "\t\tmyValue: $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 
+0

道歉的問題不夠清楚,但你得到它或多或少。我真的在尋找找到的一般元素的nodePath()。/xmlLevel1/xmlLevel2/xmlLevel3/xmlLevel4 [@名稱= '東西']/@ enableSomething /xmlLevel1/xmlLevel2 [1]/xmlLevel3/xmlLevel4 [3] /xmlLevel1/xmlLevel2 [2]/xmlLevel3/xmlLevel4 [3] –