http://qs321.pair.com?node_id=606909

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

Hey Monks,

I'm trying to migrate some code from XML::Twig to XML::LibXML for it's performance advantages. I've been trying with great difficulty to use XML::LibXML to parse dynamically created XML in which the element namespaces are not known prior to parsing. I don't care what the default namespaces are, as long as they don't get in the way.

I'm attempting to use findnodes with the recommended (from perlmonks) XML::LibXML::XPathContext module for dealing with the namespaces. Using registerNs doesn't appear to have any visible effect when printing the XML as a string, so I use $node->setNamespace to accomplish that.

my $parser = XML::LibXML->new(); my $doc = $parser->parse_file($file); my $t = $doc->getDocumentElement; foreach my $node ($t->findnodes('TransactionList/Transaction/XML')) { my $xml = $node->firstChild; my $xc = XML::LibXML::XPathContext->new($xml); foreach (qw( summary histFile fooScore )) { $xc->registerNs($_,"urn:$_"); $node->setNamespace("urn:$_",$_,0); } my $path = '//fooResponse/info/fooTransaction/transactionDetail/histFi +le:transactionSummary/summary:PacManScore'; my @nodes = $xc->findnodes($path);
I've read the two related posts to this topic: 555011 242028

...but I'm still stuck. It appears that when I encounter an element with a default namespace, findnodes refuses to match it without registering some prefix to the URI. I just want to be able to retrieve the nodes using an XPath like:

//fooResponse/info/fooTransaction/transactionDetail/histFile:transacti +onSummary/summary:PacManScore

And if I want to create new elements with arbitrary namespaces, I don't want to have to manage the namespaces at every turn.

Why does this work?
//*/info/fooTransaction/transactionDetail/*
But not this?
//*/info/fooTransaction/transactionDetail/histFile:transactionSummary/ +*

Please help! :)

I have an XML file like:
<Extract> <Service> <Name>FooService</Name> <Type>Response</Type> </Service> <TransactionList> <Transaction> <Tran_Id>90dc-2f633156cbf6</Tran_Id> <XML> <fooResponse xmlns="http://some.arbitrary.url/" xmlns:ns="http +://another.arbitrary.url/" xmlns:xsi="http://www.w3.org/2001/XMLSchem +a-instance"> <info xmlns=""> <servicePreferences> <ns:requestingCode xsi:nil="true"/> </servicePreferences> <fooTransaction xmlns:summary="foo"> <transactionDetail> <histFile:transactionSummary xmlns:histFile="http://ye +t.another.arbitrary.url/"> <summary:PacManScore>95.133</summary:PacManScore> <summary:QBertScore>95.133</summary:QBertScore> <summary:FroggerScore>95.133</summary:FroggerScore> </histFile:transactionSummary> </transactionDetail> </fooTransaction> </info> </fooResponse> </XML> </Transaction> </TransactionList> </Extract>