2015-07-19 63 views
2

爲什麼這個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()

+0

如果谷歌給你帶來了她的因爲[System.String]不包含一個名爲「StartsWith」或「IndexOf」的方法或者它實際上有的其他任何東西,可能是因爲你有類似'$ val =「DefinitelyAString」'的東西,並且正在嘗試使用某些東西像'$ val :: IndexOf(「ef」)'。這個超級可怕的錯誤應該說「使用'$ val.IndexOf(」ef「)'代替。 – StingyJack

回答

4

$xml.products沒有引用products節點本身,而是products節點的內容。由於products爲空,它將計算爲空字符串。

要到products節點,你還可以使用:

$Products = $xml.FirstChild 
$Products.AppendChild($newproduct) 

,或者更具體地說:

$Products = $xml.FirstChild.Where({$_.Name -eq "products"}) 
$Products.AppendChild($newproduct) 

SelectSingleNode()可能會竭誠爲您服務就好了

+0

由於[System.Xml.XmlElement]不包含名爲'Where'的方法,所以我得到Method調用失敗。 – Cole9350

0
$xml.configuration.SelectSingleNode("connectionStrings").AppendChild($newnode) 

會工作很好,但有趣的&骯髒的黑客:給這個空節點:

<connectionStrings>  
    </connectionStrings> 

腳本

$xml.configuration.connectionStrings.AppendChild($newnode) 

提供了一個 「Method invocation failed because [System.String] does not contain a method named 'AppendChild'」 錯誤

但這:

<connectionStrings> 
     <!-- random comment --> 
    </connectionStrings> 

工作完全正常

相關問題