http://www.perlmonks.org?node_id=1024765

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

Dear fellow Monks,

I am in receipt of an xml message. What is the best way to retrieve the xmlns (namespace) attribute from the root element of that message using XML::LibXML?? If it helps, I am expecting GovTalkMessages of the format:

<?xml version="1.0"?> <GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope"> <EnvelopeVersion>2.0</EnvelopeVersion> <Header> <MessageDetails> ..... </MessageDetails> </Header> <GovTalkDetails> ..... </GovTalkDetails> <Body> <!-- A valid Body payload with a namespace declaration on the first el +ement --> </Body> </GovTalkMessage>
For bonus points, please tell me if there is any way of avoiding using XPathContext and adding the namespace identifier to all xpath queries on the resulting DOM. e.g. do I really have to do:
my $dom = XML::LibXML->load_xml( string => $xml); my $xc = XML::LibXML::XPathContext->new($dom); $xc->registerNs( 'gt', 'http://www.govtalk.co.uk/CM/envelope'); $envelopeVersion = $xc->findvalue( '//gt:EnvelopeVersion');
A Monk aims to give answers to those who have none, and to learn from those who know more.