Search code examples
xmlperlxml-parsingxml-libxml

XML::Parsing - Unable to detect child nodes


Sample XML document

<?xml version="1.0" encoding="UTF-8"?>
<web-interface-classifier xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="WEB-INTERFACE-GROUP-CLASSIFIER.xsd" xmlns="parent/child1/granchild2/v1">
  <classifier>
      <key1>somevalue</key1>
  </classifier>
  <classifier>
      <key2>somevalue</key2>
  </classifier>
</web-interface-classifier>

Code to parse XML document above.

my $dom = XML::LibXML->load_xml(location => $filename);        
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( xsi => "http://www.w3.org/2001/XMLSchema-instance" );

foreach my $node ($xpc->findnodes("web-interface-classifier/classifier", $dom)) {
    print Dumper($node);
}

Am trying to parse the XML document and dump the needed key value pairs from the 'classifier' node, the required child nodes are not detected. Can you please provide some pointers?


Solution

  • You are trying to find elements of type web-interface-classifier and classifier from the parent/child1/granchild2/v1 namespace, but you asked to find elements of type web-interface-classifier and classifier from the null namespace. Fixed:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use v5.10;
    
    use Data::Dumper;
    use XML::LibXML;
    use XML::LibXML::XPathContext;
    
    my $dom = XML::LibXML->load_xml( IO => \*DATA );
    
    my $xpc = XML::LibXML::XPathContext->new();
    $xpc->registerNs( u => "parent/child1/granchild2/v1" );
    
    for my $node ( $xpc->findnodes( "//u:web-interface-classifier/u:classifier", $dom ) ) {
        say $node->toString();
    }
    
    __DATA__
    <?xml version="1.0" encoding="UTF-8"?>
    <web-interface-classifier xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="WEB-INTERFACE-GROUP-CLASSIFIER.xsd" xmlns="parent/child1/granchild2/v1">
      <classifier>
          <key1>somevalue</key1>
      </classifier>
      <classifier>
          <key2>somevalue</key2>
      </classifier>
    </web-interface-classifier>
    

    Outputs:

    <classifier>
          <key1>somevalue</key1>
      </classifier>
    <classifier>
          <key2>somevalue</key2>
      </classifier>