in reply to Editing in xml
in thread Append in XML using perl

Manipulating an XML document with XML::DOM is quite easy, if not a little verbose. An example that alters, deletes and adds a new child to your document:

use XML::DOM; my $xml =<<EOXML; <?xml version="1.0" encoding="windows-1252"?> <IDList><Details><id>Trial ID</id><name>Mooza </name></Details><Details><id>Trial ID</id><name>bin_salim99 </name></Details><Details><id>Trial ID</id><name>dino88 </name></Details><Details><id>Trial ID</id><name>al3neeeeed </name></Details><Details><id>TrialID</id><name>Do0oDa</name> </Details></IDList> EOXML my $parser = new XML::DOM::Parser; my $doc = $parser->parse($xml); my $root = $doc->getDocumentElement(); foreach my $detail (@{$root->getChildNodes()}) { my $name_el = $detail->getElementsByTagName('name')->[0]; my $name = $name_el->getFirstChild(); if ($name->toString() =~ /Mooza/) { my $new = $doc->createTextNode('Foobar'); $name_el->replaceChild($new, $name); } elsif ( $name->toString() =~ /Do0oDa/ ) { $root->removeChild($detail); } } my $newdet = $doc->createElement('Details'); my $new_id = $doc->createElement('id'); my $new_id_val = $doc->createTextNode('Test ID'); $new_id->appendChild($new_id_val); $newdet->appendChild($new_id); my $new_name = $doc->createElement('name'); my $new_name_val = $doc->createTextNode('Yargle'); $new_name->appendChild($new_name_val); $newdet->appendChild($new_name); $root->appendChild($newdet); print $doc->toString();
In the real world you probably would parcel the separate parts of this up in subroutines I guess.

/J\

Replies are listed 'Best First'.
Re^2: Editing in xml
by antovinraj (Initiate) on Jun 08, 2006 at 07:04 UTC
    But it is not appended in xml file but is it showin while the program is running in the command prompt. Give some comments

      Er quite, this is just an example of manipulating the XML, you can open your XML file with XML::DOM using parsefile instead of parse and writing back to the file after you have manipulating it is a trivial matter of opening a file for writing and printing $doc->toString() to it.

      /J\