在XML开头添加子节点
Add child node at the beginning of XML
我正在尝试在下面的 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')
<catalog>
是您的根节点,因此您不能将元素放在它之前,因为您将有两个根节点,这会导致您甚至无法再解析的无效 XML .
您希望使用 InsertBefore()
method,而不是 AppendChild()
:
$catalog = $a.SelectSingleNode('/catalog')
$a.InsertBefore($ammend,$catalog)
但作为 ,创建根元素的同级元素会导致无效的 XML 文档结构
对于更新后的问题,我将采用以下方法:
$catalog = $a.SelectSingleNode('/catalog')
$catalog.InsertBefore($ammend, $catalog.FirstChild)
我正在尝试在下面的 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')
<catalog>
是您的根节点,因此您不能将元素放在它之前,因为您将有两个根节点,这会导致您甚至无法再解析的无效 XML .
您希望使用 InsertBefore()
method,而不是 AppendChild()
:
$catalog = $a.SelectSingleNode('/catalog')
$a.InsertBefore($ammend,$catalog)
但作为
对于更新后的问题,我将采用以下方法:
$catalog = $a.SelectSingleNode('/catalog')
$catalog.InsertBefore($ammend, $catalog.FirstChild)