Question

I need a help for update the existing xml file attributes for given Unique ID in the xml,

Xml look like this as input

 <TextLine>
    <String ID="S14" CONTENT="Gun" SUBS_TYPE="HypPart1" SUBS_CONTENT="Gun"/>
    </TextLine>
    <TextLine>
    <String ID="S15" CONTENT="nersen" SUBS_TYPE="HypPart1" SUBS_CONTENT="nersen"/>
    </TextLine>

Output is look

<TextLine>
    <String ID="S14" CONTENT="Gun" SUBS_TYPE="HypPart1" SUBS_CONTENT="Gunnersen"/>
    </TextLine>
    <TextLine>
    <String ID="S15" CONTENT="nersen" SUBS_TYPE="HypPart1" SUBS_CONTENT="Gunnersen"/>
    </TextLine>

I am updating the SUBS_CONTENT attribute.

When i am looping Through String i can able to update current element, But i don't have next string value, After reading next line i can merge both Content and i can insert into SUBS_CONTENT

My Code looks

foreach my $PAGE1 ($pagetext->findnodes('//String')){
        my $sCurArt = $PAGE1->findvalue('@ID');
        if ($sCurArt eq $id) {
            my ($TextBlockIDx) = $PAGE1->findnodes('@SUBS_CONTENT');
                $TextBlockIDx->setValue($text);
            last;
        }
}

Please help me about this.....

Is there any way to setValue with given xml ID (S14,S15).

Thanks in advance....

Umesh

Was it helpful?

Solution

I am not 100% sure I understood your specification, but here is what I would do:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $xml = 'XML::LibXML'->load_xml(IO => *DATA{IO});

my @ids = qw(S14 S15);

my @strings = map $xml->findnodes('//TextLine/String[@ID="' . $_ . '"]'), @ids;
my $new = join q(), map $_->findvalue('@SUBS_CONTENT'), @strings;
$_->setAttribute('SUBS_CONTENT', $new) for @strings;
print $xml->toString;

__DATA__
<r>
  <TextLine>
  <String ID="S14" CONTENT="Gun" SUBS_TYPE="HypPart1" SUBS_CONTENT="Gun"/>
  </TextLine>
  <TextLine>
  <String ID="S15" CONTENT="nersen" SUBS_TYPE="HypPart1" SUBS_CONTENT="nersen"/>
  </TextLine>
</r>

I retrieve the partial strings from the XML, join them into $new, then set $new as the new value of the attributes.

OTHER TIPS

It looks like you just need the setAttribute method in XML::LibXML::Element. There is also a getAttribute method.

use strict;
use warnings;

use XML::LibXML;

my $data = do { local $/; <DATA> };

my $doc = XML::LibXML->load_xml(string => $data);

for my $node ($doc->findnodes('//String[@ID="S14" or @ID="S15"]')) {
    $node->setAttribute('SUBS_CONTENT' => 'Gunnerson');
}

print $doc->toString();

__DATA__
<root>
    <TextLine>
    <String ID="S14" CONTENT="Gun" SUBS_TYPE="HypPart1" SUBS_CONTENT="Gun"/>
    </TextLine>
    <TextLine>
    <String ID="S15" CONTENT="nersen" SUBS_TYPE="HypPart1" SUBS_CONTENT="nersen"/>
    </TextLine>
</root>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top