How can I access attributes and elements from XML::LibXML in Perl?

a 夏天 提交于 2019-12-04 06:33:28

Make sure you XML file is valid then use $node->getAttribute("someAttribute") to access attributes.

@name is a attribute name. You'd use it in findnodes() to specify elements with a given attribute set. Eg. a path like:

//camelids/species[@name="Camelus bactrianus"]/

Here is a simple/contrived example:

#!/usr/bin/perl -w
use XML::LibXML;

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file('/Users/castle/Desktop/animal.xml');

my $xc = XML::LibXML::XPathContext->new( $doc->documentElement()  );
$xc->registerNs('ns', 'http://moleculardevices.com/microplateML');

my @n = $xc->findnodes('//ns:species');
foreach $nod (@n) {
    print "A: ".$nod->getAttribute("name")."\n";

    my @c = $xc->findnodes("./ns:common-name", $nod);
    foreach $cod (@c) {
        print "B: ".$cod->nodeName;
        print " = ";
        print $cod->getFirstChild()->getData()."\n";
    }
}

Output is:

perl ./xmltest.pl 
A: Camelus bactrianus
B: common-name = Bactrian Camel
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!