我正在尝试在以下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')
答案 0 :(得分:3)
您想要使用InsertBefore()
method,而不是AppendChild()
:
$catalog = $a.SelectSingleNode('/catalog')
$a.InsertBefore($ammend,$catalog)
但是作为Martin Brandl points out,创建根元素的兄弟会导致XML文档结构无效
通过更新的问题,这将是我采取的方法:
$catalog = $a.SelectSingleNode('/catalog')
$catalog.InsertBefore($ammend, $catalog.FirstChild)
答案 1 :(得分:2)
<catalog>
是您的根节点,因此您无法将元素置于其前面,因为您将拥有两个根节点,这会导致无法解析的XML无效。