In order to be able to help much, we'll need some sample XML at the very least. But something like this might illustrate the technique:
#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig -> parse ( \*DATA ); if ( $twig -> get_xpath('/root/params/param[@name="this_setting"]') ) +{ print "Setting for \"this_setting\" already present\n"; } ## add another setting: my $add_to = $twig -> get_xpath ( '//params', 0 ); $add_to -> insert_new_elt ( 'last_child', 'param', { name => "another_ +setting" }, "Content here" ); $twig -> set_pretty_print("indented_a"); $twig -> print; __DATA__ <root> <params> <param name="this_setting"></param> <param name="that_setting"></param> </params> </root>
This will check for one parameter (using an xpath expression) but add a different one, to illustrate both. Output is:
Setting already present <root> <params> <param name="this_setting"></param> <param name="that_setting"></param> <param name="another_setting">Content here</param> </params> </root>
Assuming this is the same question on Stack Overflow I'll offer the same answer:
#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig->parsefile( 'your_file.xml' ); #search for "HostProperties" nodes within the tree. You can #be more specific about this if you need to. foreach my $HP ( $twig->get_xpath('//HostProperties') ) { #check if it has a "tag" element with a "mac-address" "name" attri +bute. if ( not $HP->get_xpath('./tag[@name="mac-address"]') ) { #insert a new element at the end of the entry. $HP->insert_new_elt( 'last_child', 'tag', { 'name' => 'mac-address' }, "DE:AD:BE:EF:F0:FF" ); } } #note - pretty printing helps reading, but might #cause some problems with certain XML constructs. Shouldn't in your sp +ecific example though. $twig->set_pretty_print("indented_a"); $twig->print; #to save it to a file: open ( my $output, '>', 'processed.xml' ) or die $!; print {$output} $twig -> sprint; close ( $output );
In reply to Re: Simple modification of XML file
by Preceptor
in thread Simple modification of XML file
by cls78628
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |