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

I am using XML::LibXML to parse my xml file that has an schema file associated with it. My xml document has namespace and schema location defined in it. When I try and parse the document to get the nodelist I get nothing, but if I remove the namespace and schema location information from the xml document it works... below is my code and part of xml file..
use XML::LibXML; my $parser = XML::LibXML->new(); my $data = $parser->parse_file($xml_file); my @nodes = $data->findnodes("/info/city");
xml_file:
<?xml version="1.0"?> <info xmlns="http://www.mydomain.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mydomain.com infoschema.xsd"> <name>john</name> <city>baltimore</city> <zip>21205</zip> </info>
do I need to set something ..am I forgetting something

Replies are listed 'Best First'.
Re: problem with using LibXML and namespace
by un-chomp (Scribe) on Oct 26, 2007 at 17:05 UTC
    If you register the namespace using XML::LibXML::XPathContext you can then use XPaths to select nodes as follows:
    #!/usr/bin/perl use strict; use warnings; use XML::LibXML; use XML::LibXML::XPathContext; # load the XML doc my $p = XML::LibXML->new; my $xml_file = do { local $/; <DATA> }; my $dom = $p->parse_string( $xml_file ); # register the namespace my $xc = XML::LibXML::XPathContext->new( $dom ); $xc->registerNs('ns', 'http://www.mydomain.com'); # select using XPath my @nodes = $xc->findnodes( '/ns:info/ns:city'); print $_->toString for @nodes; __DATA__ <?xml version="1.0"?> <info xmlns="http://www.mydomain.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mydomain.com infoschema.xsd"> <name>john</name> <city>baltimore</city> <zip>21205</zip> </info>
      Thanks un-chomp. It's working now. mjr.
Re: problem with using LibXML and namespace
by mjr1n1 (Initiate) on Oct 26, 2007 at 16:18 UTC