2015-12-14 31 views
1

我試圖消除所有孩子的,然後追加新的子代替:之後RemoveAll和AppendChild失敗?

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

但後來我得到

方法調用失敗,因爲[System.String]不包含 方法名爲'appendChild'。

由於如果刪除actaully翻XmlNodeSystem.String對象。

如何將子節點添加到空的$xml.Data節點?

+2

'$數據= $ xml.Data; $ Data.RemoveAll(); $ Data.appendChild(...)' – PetSerAl

回答

0

原來,如果xml節點上沒有子節點或屬性,則通過點訪問數據的語法將返回一個字符串。

然而節點本身可以​​通過$xml.SelectSingleNode進行訪問,即使它是空的:

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

如果一個元素沒有子元素並且沒有屬性,那麼PowerShell將其評估爲一個字符串。在你的例子中調用RemoveAll()後,這就是發生在「Data」元素中的情況。

我不知道爲什麼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 
相關問題