#!/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>

In reply to Re: libxml - insert node by tobyink
in thread libxml - insert node by Styric

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.