Search code examples
xmlpowershellparent-childchild-nodes

Add child node at the beginning of XML


I am trying to add a child node in the following XML. I am able to, but my issue is it adds it at the end. How am I able to add the node at the beginning between <catalog> and <book>?

<?xml version="1.0"?>
 <catalog>
 <book id="bk101">
   <author>Gambardella, Matthew</author>
   <title>XML Developer's Guide</title>
   <genre>Computer</genre>
   <price>44.95</price>
   <publish_date>2000-10-01</publish_date>
   <description>An in-depth look at creating applications 
   with XML.</description>
 </book>
 <book id="bk102">
   <author>Ralls, Kim</author>
   <title>Midnight Rain</title>
   <genre>Fantasy</genre>
   <price>5.95</price>
   <publish_date>2000-12-16</publish_date>
   <description>A former architect battles corporate zombies, 
   an evil sorceress, and her own childhood to become queen 
   of the world.</description>
  </book>
  </catalog>

My code is:

 [xml]$a = Get-Content 'C:\Users\me\Documents\Scripts\books.xml'
 $ammend =$a.CreateElement("Quarter")
 $a.DocumentElement.AppendChild($ammend)
 $a.save('C:\Users\me\Documents\Scripts\books.xml')

Solution

  • You'd want to use the InsertBefore() method, rather than AppendChild():

    $catalog = $a.SelectSingleNode('/catalog')
    $a.InsertBefore($ammend,$catalog)
    

    But as Martin Brandl points out, creating a sibling to the root element would result in an invalid XML document structure


    With the updated question, this would be the approach I'd take:

    $catalog = $a.SelectSingleNode('/catalog')
    $catalog.InsertBefore($ammend, $catalog.FirstChild)