What is wrong with this findnodes statement in my Perl script?

I have a simple XML file that looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <microplateDoc xmlns="http://moleculardevices.com/microplateML"> <camelids> <species name="Camelus bactrianus"> <common-name>Bactrian Camel</common-name> <physical-characteristics> <mass>450 to 500 kg.</mass> <appearance> Blah blah blah </appearance> </physical-characteristics> </species> </camelids> </microplateDoc> 

I am trying to read view names with the following perl script:

 use XML::LibXML; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file('/Users/johncumbers/Documents/7_Scripts/Perl/XML_to_MySQL/simplified_camelids.xml'); my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() ); $xc->registerNs('ns', 'http://moleculardevices.com/microplateML'); #loop through to find species nodes my @n = $xc->findnodes('*/species'); #was */species foreach $nod (@n) { print "A: ".$nod->getAttribute("name")."\n"; my @c = $nod->findnodes('./common-name'); } 

But I can not find any nodes. Can you help me and explain why it does not work? What is the best website to search for perl functions so that I can try to solve the problem myself? How can I get a script to tell me what it is doing, since the output at the moment is just nothing. Many thanks.

+6
perl xpath libxml2
source share
1 answer

You have associated the namespace prefix with the document, but your XPath syntax does not use it.

 my @n = $xc->findnodes('//ns:species'); 

must do the job.

Without a prefix, you will not match. Also, the */species path will only correspond to children in the current context (i.e., at the top level of the document). Using //species will find all species elements in the document. If this does not work for you (since the element appears in some other context in the document that you do not want to map) use

 /*/*/ns:species 

since this element is a "great grandson" of the upper level.

Another XPath link.

+5
source share

All Articles