Add child node at the beginning of XML

亡梦爱人 提交于 2019-12-10 23:58:52

问题


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.



来源:https://stackoverflow.com/questions/38874588/add-child-node-at-the-beginning-of-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!