我有一个xml列表,我希望在<game>
下添加一个新的子元素。我已经能够将子元素附加到游戏节点块的末尾,但是对于命名标准,我需要在图像元素之后插入它作为图像的兄弟。
<image>
<marquee>
XML文档:
<?xml version="1.0" encoding="UTF-8"?>
<gameList>
<game id="2758" source="theGamesDB.net">
<path>./Zelda II - The Adventure of Link (USA).zip</path>
<name>Zelda II - The Adventure of Link (USA)</name>
<desc>Removed description for example</desc>
<image>./boxart/Zelda II - The Adventure of Link (USA).png</image>
<rating>0.68333</rating>
<releasedate>19880926T000000</releasedate>
<developer>Nintendo</developer>
<publisher>Nintendo</publisher>
<genre>Action</genre>
<players>1</players>
</game>
</gamelist>
我的代码在代码块的末尾追加一个选框子元素。 注意:这是针对每个循环遍历大量游戏的循环。为简单起见,我已经取出了创建选取路径位置的代码并对其进行了硬编码。
#Set the name of the game list
$InputXML = "gamelist.xml"
$OutputXML = "MODgamelist.xml"
#Load the existing document
[xml]$xml = Get-Content $InputXML
foreach($game in $xml.gamelist.game)
{
#Set Marquee Path
$marqueelPath = "./Zelda II - The Adventure of Link (USA).png"
#Add marquee node to game node parent
$marqueeElement = $xml.CreateElement("marquee")
$marqueeElement.InnerText = $marqueelPath
$game.AppendChild($marqueeElement)
}
#Output
$xml.save($OutputXML)
经过一番挖掘后,我想出了这个代码,在图像之后插入新的子元素,但是它出错了。如何正确选择图像节点然后插入?
$imageElement = $game.SelectSingleNode('//image')
$game.InsertAfter($marqueeElement, $imageElement)
错误:
Exception calling "InsertAfter" with "2" argument(s): "The reference node is not a child of this node."
At line:1 char:1
+ $game.InsertAfter($marqueeElement, $imageElement)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
提前致谢。
答案 0 :(得分:0)
我正在阅读MSDN文档并制定了解决方案。 https://msdn.microsoft.com/en-us/library/k44daxya.aspx
由于所有游戏节点块的布局都相同,我实际上可以通过数组编号调用参考节点。
#Add marquee node to game node parent
$marqueeElement = $xml.CreateElement("marquee")
$marqueeElement.InnerText = $marqueelPath
$game.InsertAfter($marqueeElement, $game.ChildNodes[3])
答案 1 :(得分:0)
这是一岁的帖子,我对此没有看到可接受的答案,但是在上面的评论中,@ har07的建议对我有用。您希望这两个节点是同一父元素的子节点,一个插入在另一个之后。首先,您需要获取父节点,然后在对我有用的父节点上调用InsertAfter(newNode,refNode)方法。使用OP的代码:
$ParentNode = $imageElement.ParentNode
$ParentNode.InsertAfter($marqueeElement, $imageElement)