So, it turns out inserting a new node into an existing xml list is not as easy as I thought. I'm sure I'm missing something but been tinkering with this for quite some time now so I ask you for some guidance.

In short, I'm using a file as a base model which is being read in that looks similar to this.

<top> <nodes> <node> <label>Office</label> <node> <label>1st Floor</label> </node> <node> <label>2nd Floor</label> </node> <node> <nodes> </top>
Say I want to add something to the 1st floor like this. <node> <label>10.1.1.1</label> </node> I've gone through many different variations so I'll post one of them as the closest I can come is appending it to the end and not to the floor I want.
#!/usr/bin/perl use XML::LibXML; $filename = "Office.xml"; my $floor = '1st Floor'; my $bldg = "Building A"; my $parser = XML::LibXML->new(); my $doc = $parser->parse_file("$filename") or die; my $root = $doc->getDocumentElement(); my $parent = $doc->documentElement; my $newnode = $doc->documentElement; my $query = "//node[label = '$bldg']/node[label = '$floor']/label/tex +t()"; if(my($node) = $doc->findnodes($query)) { my $new_element= $doc->createElement("IP"); $new_element->appendText('10.1.1.1'); $newnode = $parent->addSibling($new_element); print $newnode -> toString; }
Can someone please help?

In reply to 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.