Reputation: 62
I was trying to add a block of content under some xpath in the existing XML file. I was new to this XML parsing using Perl. But I was supposed to do using this XML::Twig.
Input :
<model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
<schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
<bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
<para>
<root>
<row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
</root>
</para>
</bean>
</schema>
</appli>
Output:
<model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
<schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
<bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
<para>
<root>
<row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
<row name="INTERNAL" desc="" value="">
<row name="PATH" desc="Path" value="#PATH#" />
<row name="EXT" desc="Adresse" value="#GAIAIP#" />
</row>
</root>
</para>
</bean>
</schema>
</appli>
Upvotes: 0
Views: 835
Reputation: 132920
For XML::Twig, create a handler to modify the element you want to change. In that handler, create the new elements that you want then paste them into the element as children:
use XML::Twig;
my $xml = <<'HERE';
<model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
<schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
<bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
<para>
<root>
<row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
</root>
</para>
</bean>
</schema>
</appli>
</model>
HERE
my $twig = XML::Twig->new(
twig_handlers => {
'bean/para/root' => \&add_rows,
},
pretty_print => 'indented',
);
$twig->parse( $xml );
$twig->print;
Remember that in the handler, you get the current element as $_
:
sub add_rows {
XML::Twig::Elt->new( row => {
name => 'PATH',
desc => 'Path',
value => '#PATH#'
} )->paste( last_child => $_ );
XML::Twig::Elt->new( row => {
name => 'EXT',
desc => 'Adresse',
value => '#GAIAIP#'
} )->paste( last_child => $_ );
}
Upvotes: 2