access sub child value by libxml::xpathcontext

115 views Asked by At

I want to access the value of sub child and modify it. This is my xml

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

and this is my code

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://blablabla');

for my $node ($context->findnodes('//u:inner') ) {
    for my $node2 ($node->findnodes('//u:name') ) {
         #if (($node->findnodes('u:name', $node2) ->size) != 1) {next;}
         my ($mh)   = $node->findnodes('u:prenom', $node2);
         my $size  = $node->findnodes('u:prenom', $node2) ->size;
         print "size $size";
         if ($size != 1) {next;}
         $mh ->removeChildNodes();
         $mh->appendText('World12456');
         print "mh = $mh";
    }
}

I want to access prenom and modify it to 'World12456'. With currrent code; I got this error XPath error : Undefined namespace prefix error : xmlXPathCompiledEval: evaluation failed. Then I tried different way

for my $node ($context->findnodes('//u:inner') ) {
         my ($mh)   = $context->findnodes('u:name/prenom', $node);
         my $size  = $context->findnodes('u:name/prenom', $node) ->size;
         print "size $size";
         if ($size != 1) {next;}
         $mh ->removeChildNodes();
         $mh->appendText('World12456');
         print "mh = $mh";
}

Then I get the size is 0 for both. It doesn't find the tag prenom. With

for my $node ($context->findnodes('//u:inner/name')

It displays nothing.

I am sorry if this is duplicate but I don't find any link to access the sub child with xpathcontext yet.

1

There are 1 answers

0
user3922604 On

I got it . I just need to put u for each element

for my $node ($context->findnodes('//u:inner/u:name')