我正在尝试在以下XML中添加子节点。我能够,但是我的问题是最后添加了它。如何在<catalog>
和之间的开头添加节点<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>
我的代码是:
[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')
您想使用InsertBefore()
方法,而不是AppendChild()
:
$catalog = $a.SelectSingleNode('/catalog')
$a.InsertBefore($ammend,$catalog)
但是正如Martin Brandl指出的那样,为根元素创建同级将导致无效的XML文档结构
有了更新的问题,这就是我要采用的方法:
$catalog = $a.SelectSingleNode('/catalog')
$catalog.InsertBefore($ammend, $catalog.FirstChild)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句