in reply to Appending Text of One XML Node to that of the Other

Hello thomasd

your XML has the </MsgSigs> closing tag missing.. corrected this I as always propose an XML::Twig based solution. Infact navigation methods as summarized here (the site has also good tutorials!) make the life of an XML traveller easier.

Note also that twig_handlers plus flush make the program very memory efficient: for every xdoc/MsgSigs/MsgSig two child are inspected and the first manipulated, then flush prints all the twig parsed till now and memory is freed.

#!perl use strict; use warnings; use XML::Twig; my $t= XML::Twig->new(pretty_print => 'indented', twig_handlers=>{ 'xdoc/MsgSigs/MsgSig'=>sub{ my $keytext = $_[1]->first_child('Key')->text; my $descrtext = $_[1]->first_child('Description') +->text; $_[1]->first_child('Description')->set_text($desc +rtext." ($keytext)"); $_[0]->flush; } } ); $/=''; $t->parse(<DATA>); __DATA__ <xdoc> <MsgSigs> <MsgSig> <Description>TSC1 - Torque/Speed Cntrl 1</Description> <Key>ln1</Key> <XtdFrame>True</XtdFrame> <NetworkKey>net0</NetworkKey> <MsgSignals> </MsgSignals> </MsgSig> <MsgSig> <Description>TSC1 - Torque/Speed Cntrl 1</Description> <Key>ln2</Key> <XtdFrame>True</XtdFrame> <NetworkKey>net0</NetworkKey> <MsgSignals> <Signal> <Description>0_SPN695 Eng. Override </Description> <Key>sig695</Key> <ValueType>1</ValueType> </Signal> </MsgSignals> </MsgSig> </MsgSigs> </xdoc> ###OUTPUT <xdoc> <MsgSigs> <MsgSig> <Description>TSC1 - Torque/Speed Cntrl 1 (ln1)</Description> <Key>ln1</Key> <XtdFrame>True</XtdFrame> <NetworkKey>net0</NetworkKey> <MsgSignals></MsgSignals> </MsgSig> <MsgSig> <Description>TSC1 - Torque/Speed Cntrl 1 (ln2)</Description> <Key>ln2</Key> <XtdFrame>True</XtdFrame> <NetworkKey>net0</NetworkKey> <MsgSignals> <Signal> <Description>0_SPN695 Eng. Override </Description> <Key>sig695</Key> <ValueType>1</ValueType> </Signal> </MsgSignals> </MsgSig> </MsgSigs> </xdoc>

HtH

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Appending Text of One XML Node to that of the Other -- XML::Twig
by thomasd (Initiate) on Feb 05, 2016 at 18:14 UTC

    Thank-you very much. I hadn't actually gotten around to Twig yet. Very clean, quick and efficient.