slong16 slong16 - 1 year ago 162
PowerShell Question

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


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

My code is:

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

Answer Source

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

$catalog = $a.SelectSingleNode('/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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download