RemoveAll和AppendChild之后失败了吗?

时间:2015-12-14 11:23:18

标签: xml powershell

我正在尝试删除所有孩子,然后添加一个新孩子:

$xml.Data.RemoveAll()
$xml.Data.appendChild( ... )

但后来我

  

方法调用失败,因为[System.String]不包含   名为'appendChild'的方法。

好像删除操作将XmlNode转换为System.String对象。

如何将子节点添加到空$xml.Data节点?

2 个答案:

答案 0 :(得分:1)

如果xml节点上没有子节点或属性,则通过点访问数据的语法返回一个字符串。

然而,即使节点为空,也可以通过$xml.SelectSingleNode访问节点本身:

$xml.Data.RemoveAll()
$xml.SelectSingleNode("/Data").appendChild( ... )

答案 1 :(得分:0)

如果元素没有子元素且没有属性,那么PowerShell会将其作为字符串进行评估。这就是"数据"正在发生的事情。调用RemoveAll()后,示例中的元素。

我不知道为什么PowerShell会这样做,或者如何阻止它。作为一种解决方法,我建议强制Powershell处理"数据"通过添加临时属性作为元素。添加新的子元素后,删除临时属性。例如:

#Set-up
$xml = new-object System.Xml.XmlDocument
$xml.LoadXml("<Data><A1/><A2><B1/><B2/></A2></Data>")
$xml.Data.RemoveAll()

#Add a temporary attribute to "Data"
$temporaryAttribute = $xml.CreateAttribute("temp")
$xml.SelectSingleNode("/Data").attributes.append($temporaryAttribute) | out-null

#Add new children
$newChild = $xml.CreateElement("NewChild")
$xml.Data.appendChild($newChild) | out-null
#Add next new child etc. etc.

#When done, remove the temporary attribute
$xml.Data.Attributes.Remove($temporaryAttribute) | out-null

#View the result
$xml.OuterXml