爲什麼這個PowerShell腳本不工作:爲什麼錯誤 「System.String不包含命名方法 '的appendChild'」
[xml]$xml = '<products></products>'
$newproduct = $xml.CreateElement('product')
$attr = $xml.CreateAttribute('code')
$attr.Value = 'id1'
$newproduct.Attributes.Append($attr)
$products = $xml.products
$products.AppendChild($newproduct)
錯誤是
Method invocation failed because [System.String] does not contain a method named 'AppendChild'.
At line:1 char:1
+ $products.AppendChild($newproduct)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
如果我更換
$products = $xml.products
來自
$products = $xml.SelectSingleNode('//products')
它會工作,但我想知道爲什麼第一種語法不起作用,因爲它對我來說不合邏輯。 $xml.products
應該是一個有效的XML對象,因此提供方法AppendChild()
。
如果谷歌給你帶來了她的因爲[System.String]不包含一個名爲「StartsWith」或「IndexOf」的方法或者它實際上有的其他任何東西,可能是因爲你有類似'$ val =「DefinitelyAString」'的東西,並且正在嘗試使用某些東西像'$ val :: IndexOf(「ef」)'。這個超級可怕的錯誤應該說「使用'$ val.IndexOf(」ef「)'代替。 – StingyJack