I have an xml with default namespace something like this:
<?xml version="1.0" encoding="utf-8"?>
<start xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://127.0.0.1 GrammarXSD.xsd" version="01.00" xmlns="GrammarXSD.xsd">
<DataModel>
#rest of the xml
</DataModel>
</start>
To parse this xml, I am trying to register the namespace using the following code:
my $file = "xml file location";
my $dom = XML::LibXML->load_xml(location => $file);
my $xpc = XML::LibXML::XPathContext->new($dom->documentElement());
$xpc->registerNs('ns', 'GrammarXSD.xsd');
my $b = $dom->findnodes('//ns:DataModel');
However this is not finding the DataModel nodes as expected. The GrammarXSD.xsd file is in the same location as the xml.
What am I missing here?
You have to use the XPathContext object to search for nodes in a namespace-aware way:
my $data_models = $xpc->findnodes('//ns:DataModel', $dom);
BTW, don't use my $b
, $b is a special variable used in sort and declaring it as lexical can cause bugs if sort
is used later in the same scope.
Also, the namespace URI doesn't mean anything, it just identifies the namespace.