in reply to libxml - insert node

#!/usr/bin/perl use strict; use XML::LibXML 1.70; # Parse the document. XML::LibXML 1.70 introduced the load_xml method, # which is somewhat nicer than the pre-1.70 methods for parsing data. my $doc = XML::LibXML->load_xml(IO => \*DATA) or die; # In your original example, the building was "Building A", but there # was no node called "Building A" in the sample XML. my $bldg = 'Office'; my $floor = '1st Floor'; # I've changed your query so that it selects a <node> element. # Previously it drilled down further to select the text inside # the node's <label> element. There didn't seem to be any reason # to do that. my $query = "//node[label = '$bldg']/node[label = '$floor']"; # Here's one way to do it... if( my ($node) = $doc->findnodes($query) ) { my $new_node = $doc->createElement("node"); my $new_label = $doc->createElement("label"); $node->addChild($new_node); $new_node->addChild($new_label); $new_label->appendText('10.1.1.1'); } # This way is a little more concise... if( my ($node) = $doc->findnodes($query) ) { $node -> addNewChild(undef, 'node') -> addNewChild(undef, 'label') -> appendText('10.2.2.2'); } # This outputs the XML nicely indented. If you don't care # about indentation, just use print $doc->toString. use XML::LibXML::PrettyPrint; print XML::LibXML::PrettyPrint -> new ( element => { compact => [qw/label/] } ) -> pretty_print($doc) -> toString; __DATA__ <top> <nodes> <node> <label>Office</label> <node> <label>1st Floor</label> </node> <node> <label>2nd Floor</label> </node> </node> </nodes> </top>

Replies are listed 'Best First'.
Re^2: libxml - insert node
by Styric (Initiate) on Feb 15, 2012 at 06:27 UTC
    Thanks Tobyink! Although your updated method of node inserting worked, your more "precise" method returned some errors and will post them later. Never the less, one worked, that's all that matters! :)