在XML开头添加子节点

时间:2021-02-14 23:48:35

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中添加子节点。我有能力,但我的问题是它在最后添加了它。如何在 之间添加节点?

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

2 个解决方案

#1


3  

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

您希望使用InsertBefore()方法,而不是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

但是正如Martin Brandl所指出的,为根元素创建一个兄弟元素将导致无效的XML文档结构


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

有了最新的问题,我将采取以下方法:

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

#2


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.

是根节点,因此不能将元素放在它之前,因为您将有两个根节点,这将导致一个无效的XML,您甚至无法再解析它。

#1


3  

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

您希望使用InsertBefore()方法,而不是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

但是正如Martin Brandl所指出的,为根元素创建一个兄弟元素将导致无效的XML文档结构


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

有了最新的问题,我将采取以下方法:

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

#2


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.

是根节点,因此不能将元素放在它之前,因为您将有两个根节点,这将导致一个无效的XML,您甚至无法再解析它。