Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

XML namespaces

by corfuitl (Sexton)
on Jul 24, 2018 at 16:17 UTC ( #1219176=perlquestion: print w/replies, xml ) Need Help??

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

Hi perlmonks

It seems that my code is not able to parse this XML because of the "xmlns="urn:foo:names:tc:doc:document:1.2""

I tried to use registerNs but no luck :(

Could you please help me on this?

Here is the XML

<?xml version="1.0" encoding="UTF-8"?> <doc version="1.2" xmlns="urn:foo:names:tc:doc:document:1.2" xmlns:okp +="ok-fr:doc-extensions" xmlns:its="" x +mlns:itsxlf="" its:version="2.0"> <body> </body> <body> <node id="NFDBB2FA9-tu1" xml:space="preserve"> <node1>TEXT 1"</node1> </node> </body> </doc>

And here is my code

use XML::LibXML; my $dom = 'XML::LibXML'->load_xml(IO => *STDIN); foreach my $tu ($dom->findnodes('/doc/body/node')) { for my $node ($tu->findnodes('node1')) { print "$node\n"; } }

Replies are listed 'Best First'.
Re: XML namespaces
by haukex (Bishop) on Jul 24, 2018 at 16:33 UTC
    I tried to use registerNs but no luck :(

    When you use XML::LibXML::XPathContext, remember to call findnodes on that object for the namespaces to take effect. The following works fine for me (output "<node1>TEXT 1"</node1>") for your example file. Note how I'm passing the context of the second findnodes call as the second argument, and I adjusted your XPath expressions to use the namespace, since it applies to all nodes in the document.

    use warnings; use strict; use XML::LibXML; my $doc = XML::LibXML->load_xml( location => '/tmp/foo.xml' ); my $xpc = XML::LibXML::XPathContext->new($doc); $xpc->registerNs('foo', 'urn:foo:names:tc:doc:document:1.2'); foreach my $tu ($xpc->findnodes('/foo:doc/foo:body/foo:node')) { for my $node ($xpc->findnodes('foo:node1', $tu)) { print "$node\n"; } }
Re: XML namespaces
by Corion (Pope) on Jul 24, 2018 at 16:22 UTC

    You don't tell us what error message you get or how you used ->registerNs to register your namespace.

    I've used XML::LibXML with namespaces and ->findnodes and I'm fairly certain that they work. Maybe the problem is your XPath expression - doc is different from foo:doc, if foo is the namespace urn:foo:names:tc:doc:document:1.2 where the doc element lives in. Maybe changing your XPath query to the following will make things work if you specify the namespaces for each node not in th edefault namespace:


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2021-03-02 12:18 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (46 votes). Check out past polls.