in reply to XML handling

Showing us a sample of the code you have tried, or at least telling us what modules you are using, would help a great deal in providing a good answer.

A light weight way to perform your trick if you are not fussy about the order of the elements in the result is:

use strict; use XML::Simple; my $org = <<'XML'; <FILER url='http://somewhere'> <PROJECT name='test_project'/> <USER email='some@email.com'/> </FILER> XML # parse the input string my $root = XMLin ($org, KeepRoot => 1, ); # Insert the element $root->{FILER}{LOCATION}{name} = '1stFloor'; # Dump the result print XMLout ($root, RootName => undef);

which prints:

<FILER url="http://somewhere"> <LOCATION name="1stFloor" /> <PROJECT name="test_project" /> <USER email="some@email.com" /> </FILER>

If you need to retain the original element order then you need something like XML::TreeBuilder:

use strict; use XML::TreeBuilder; my $org = <<'XML'; <FILER url='http://somewhere'><PROJECT name='test_project'/><USER emai +l='some@email.com'/></FILER> XML # parse the input string my $root = XML::TreeBuilder->new (); $root->parse ($org); # Insert the element my $ins = XML::Element->new ('LOCATION', name => '1stFloor'); $root->push_content ($ins); # Dump the result print $root->as_XML ();

which prints:

<FILER url="http://somewhere"><PROJECT name="test_project"></PROJECT>< +USER email="some@email.com"></USER><LOCATION name="1stFloor"></LOCATI +ON></FILER>

or XML::Twig:

use strict; use XML::Twig; my $org = <<'XML'; <FILER url='http://somewhere'><PROJECT name='test_project'/><USER emai +l='some@email.com'/></FILER> XML # parse the input string my $root = XML::Twig->new (); $root->parse ($org); # Insert a new element my $ins = XML::Twig::Elt->new ('LOCATION', {name => '1stFloor'}); $ins->paste ('last_child', $root->root ()); # Dump the result $root->print ();

which prints:

<FILER url="http://somewhere"><PROJECT name="test_project"/><USER emai +l="some@email.com"/><LOCATION name="1stFloor"/></FILER>

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: XML handling
by derby (Abbot) on Sep 17, 2007 at 11:50 UTC

    Or XML::LibXML

    !/usr/bin/perl use strict; use warnings; use XML::LibXML; my $xml = <<'XML'; <FILER url='http://somewhere'> <PROJECT name='test_project'/> <USER email='some@email.com'/> </FILER> XML my $parser = XML::LibXML->new(); my $doc = $parser->parse_string( $xml ); my $node = $doc->createElement( 'LOCATION' ); $node->setAttribute( 'name', '1stFloor' ); my $root = $doc->documentElement(); $root->appendChild( $node ); print $doc->toString(), "\n";

    -derby