bigallow has asked for the wisdom of the Perl Monks concerning the following question:

Hello dear Monks, I`m kinda new to perl and xml, but anyway, here is my problem: 1. I have a xml file (url_config.xml) like this:
<?xml version="1.0"?> <urls> <url id="1" link="http://localhost/index.php?page=news&amp;id_news=1 +" name="First Test Name" /> <url id="2" link="http://localhost/index.php?page=news&amp;id_news=1 +7" name="2-nd test name with 2 as id" /> <url id="4" link="http://localhost/index.php?page=news&amp;id_news=5 +" name="another cool link" /> </urls>
2. using perl and XML::DOM i want to add a new line to the url_config.xml file, in the end this file should look like this:
<?xml version="1.0"?> <urls> <url id="1" link="http://localhost/index.php?page=news&amp;id_news=1 +" name="First Test Name" /> <url id="2" link="http://localhost/index.php?page=news&amp;id_news=1 +7" name="2-nd test name with 2 as id" /> <url id="4" link="http://localhost/index.php?page=news&amp;id_news=5 +" name="another cool link" /> <url id="5" link="http://localhost/index.php?page=news&amp;id_news=2 +3" name="another cool link added later on" /> </urls>
3. I know how to read the xml file, I know how to parse the file but i don`t know how to insert a new row.
#!/usr/bin/perl -w use XML::DOM; my $parser = new XML::DOM::Parser; my $doc = $parser->parsefile ("url_config.xml"); my $nodes = $doc->getElementsByTagName( "url" ); my $entries = $nodes->getLength; my @id_array; # insert all the id`s in a array: for (my $i = 0; $i < $entries; $i++) { my $node = $nodes->item ($i); my $href = $node->getAttributeNode ("id"); print $href->getValue . "\n"; push(@id_array, $href->getValue); } # last id: my $last_id = pop(@id_array); print $last_id; print "\n"; print "total no. of records::" . $entries . "\n";

Replies are listed 'Best First'.
Re: XML::DOM -> writing
by bigallow (Initiate) on Jun 02, 2004 at 15:50 UTC
    I got it!!! So, actually the fallowing lines is what i`m looking for:
    my $root = $doc->getDocumentElement(); my $whole_node = $doc->createElement("url"); $whole_node->setAttribute("id","14"); $whole_node->setAttribute("link","http://www.yahoo.com"); $whole_node->setAttribute("name","The first link I ever saw"); $root->appendChild( $whole_node );
    Right now the problem is that in the xml file the text is not so well formated :( (is this a real problem?) What do you thing this is the right solution, or there is a simple way to add comtent to that xml file?