in reply to XML::Simple--dealing with a variable element
You may find XML::TreeBuilder more suited to your task:
use warnings; use strict; use XML::TreeBuilder; my $str = <<'STR'; <dataschemas> <dataschema name="varyingName1"> <attributes> <attribute> attr 1 attr 2 </attribute> </attributes> </dataschema> <dataschema name="varyingName2"> <attributes> <attribute> attr 1 attr 3 </attribute> </attributes> </dataschema> </dataschemas> STR my $xml = XML::TreeBuilder->new; $xml->parse($str); my @attributes = $xml->find('attribute'); for (@attributes) { # Figure out where the element is my @lineage = reverse $_->lineage (); my @eNames = map {$_->tag() . ($_->attr('name') ? '(' . $_->attr('name') . +')' : '')} @lineage; print join ('/', @eNames), ":\n"; # Access the element text my $oldText = $_->as_text(); print "$oldText\n"; # Alter the content $_->push_content ("Extra attribute added"); } print $xml->as_HTML ('<>&', ' '); # Looks bogus, but gets indentation
Prints:
dataschemas/dataschema(varyingName1)/attributes: attr 1 attr 2 dataschemas/dataschema(varyingName2)/attributes: attr 1 attr 3 <dataschemas> <dataschema name="varyingName1"> <attributes> <attribute> attr 1 attr 2 Extra attribute added</attribute> </attributes> </dataschema> <dataschema name="varyingName2"> <attributes> <attribute> attr 1 attr 3 Extra attribute added</attribute> </attributes> </dataschema> </dataschemas>
Update: added editing sample code
|
|---|