Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

XML::LibXML findnodes fails when using namespaces

by jeteve (Pilgrim)
on Jun 13, 2006 at 12:05 UTC ( #555011=perlquestion: print w/replies, xml ) Need Help??

jeteve has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellow monks.

I'm using XML::LibXML to edit xml files but I'm stucked to this problem:

When the root element of my document has an xmlns attributes, the findnodes method fails to give me the node I want.

Here is a test code:
use XML::LibXML ; my $xml = q{<?xml version="1.0" encoding="iso-8859-1"?> <Tag1 xmlns="wow"> <Foo>content</Foo> </Tag1> }; my $xml2 = q{<?xml version="1.0" encoding="iso-8859-1"?> <Tag1> <Foo>content</Foo> </Tag1> }; my $parser = XML::LibXML->new(); my $doc1 = $parser->parse_string($xml); my ($foo) = $doc1->findnodes('/Tag1/Foo'); print "Foo in xml: ".$foo."\n"; ## Gives undef (with xmlns) my $doc2 = $parser->parse_string($xml2); my ($foo2) = $doc2->findnodes('/Tag1/Foo'); ## IS OK (without xmlns) print "Foo in xml2: ".$foo2->textContent()."\n" ;
Can anybody help ? I searched how to make the parser namespace negligent but I didn't find. Thanks . J.

-- Nice photos of naked perl sources here !

Replies are listed 'Best First'.
Re: XML::LibXML findnodes fails when using namespaces
by gellyfish (Monsignor) on Jun 13, 2006 at 12:31 UTC

    You need to register the namespace, this is made easy with XML::LibXML::XPathContext:

    use XML::LibXML; use XML::LibXML::XPathContext; + my $xml = q{<?xml version="1.0" encoding="iso-8859-1"?> <Tag1 xmlns="urn:wow"> <Foo>content</Foo> </Tag1> }; + + + my $doc = XML::LibXML->new->parse_string($xml); my $xc = XML::LibXML::XPathContext->new($doc); $xc->registerNs('foo', 'urn:wow'); + my ($foo) = $xc->findnodes('//foo:Tag1/foo:Foo'); + print "Foo in xml: ".$foo->textContent()."\n";
    You can register any arbitrary prefix to your namespace URI to use in your XPath expression but note I have changed your namespace to an absolute URI as you get an error from XML::LibXML otherwise.


Re: XML::LibXML findnodes fails when using namespaces
by tomhukins (Curate) on Jun 13, 2006 at 15:41 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://555011]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2021-06-12 13:44 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (52 votes). Check out past polls.