LibXML : colon in removeAttribute and value in getAttribute

466 views Asked by At

This is my xml file

 <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
    <outer1  xmlns="http://blablabla">
      <inner1>
        <name>Hello</name>
        <org>wwf</org>
        <profession>warrior</profession>
      </inner1>
    </outer1>
  </config>

I want to do two things

  1. Get the attribute value from config and outer1
  2. Delete the attribute

This is the perl code

use strict;
use warnings;
use XML::LibXML;

my $xml = "Sample3.xml";

my $parser =XML::LibXML->new();
my $tree   =$parser->parse_file($xml);
my $root   =$tree->getDocumentElement;
print $root->getAttribute('xmlns:xc'), "\n";
print $root->getAttribute('/config/outer1/@xmlns'), "\n"; --> not working

$root->removeAttribute('xmlns:xc');--> not working
print "$tree->toString";

The output should be

<config>
        <outer1>
          <inner1>
            <name>Hello</name>
            <org>wwf</org>
            <profession>warrior</profession>
          </inner1>
        </outer1>
      </config>

I managed to get the value of xmlns:xc but not for xmlns. I tried the other way with $root->findvalue('/config/outer1/@xmlns'); but still not returning the value of xmlns. The other problem is removeAttribute. It doesn't recognize colon inside xmlns:xc but it does in getAttribute. I dont get why

Thanks in advance

2

There are 2 answers

17
choroba On

In order to use namepsaces with XML::LibXML, use XML::LibXML::XPathContext:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use XML::LibXML;

my $xml = 'XML::LibXML'->load_xml( string =>
'<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
    <outer1  xmlns="http://blablabla">
      <inner1>
        <name>Hello</name>
        <org>wwf</org>
        <profession>warrior</profession>
      </inner1>
    </outer1>
  </config>');

my $xpc = 'XML::LibXML::XPathContext'->new;
$xpc->registerNs('b', 'http://blablabla');

say for $xpc->findnodes('/config/b:outer1', $xml);
#                               ^^^
0
user3922604 On
my $dom = XML::LibXML->load_xml( location => $xml);
my $context = XML::LibXML::XPathContext->new( $dom->documentElement() );
$context->registerNs( 'u' => '"urn:ietf:params:xml:ns:netconf:base:1.0' );
$context->registerNs( 'u' => 'http://alcatel-lucent.com/lte/enb');

for my $node ( $context->findnodes('//u:inner1[1]') ) {
 my ($mh)   = $context->findnodes('u:name', $node);
    $mh ->removeChildNodes();
    $mh->appendText('World123');
    print $dom->toString;

@Choroba : I got it. It should be $mh not $context. Thanks for your suggestion. And one more, why should put my ($mh) instead of my $mh? @all: Thanks for the advice too