【问题标题】:RemoveAll and AppendChild afterwards fails?RemoveAll 和 AppendChild 之后失败了吗?
【发布时间】:2015-12-14 11:23:17
【问题描述】:

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

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

然后我明白了

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

好像删除实际上将XmlNode 变成了System.String 对象。

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

【问题讨论】:

  • $Data=$xml.Data; $Data.RemoveAll(); $Data.appendChild( ... )

标签: xml powershell


【解决方案1】:

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

但是节点本身可以​​通过$xml.SelectSingleNode访问,即使它是空的:

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

【讨论】:

    【解决方案2】:

    如果一个元素没有子元素且没有属性,则 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      相关资源
      最近更新 更多