Add child node at the beginning of XML

2019-07-11 18:20发布

问题:

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')

回答1:

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)


回答2:

<catalog> is your root node so you can't place the element before it because you would have two root nodes which would result in an invalid XML that you can't even parse anymore.