我有以下XML
樹:PowerShell的:添加子節點XML
<company>
<employees>
<employee name="Dwight" id="e1000" department="sales">
</employee>
<employee name="Toby" id="e1001" department="hr">
</employee>
<employee name="Jim" id="e1002" department="sales">
</employee>
</employees>
</company>
而且我想在部門=「接待」添加一個名爲帕姆新員工,ID =「E1003」。
這是我到目前爲止已經試過:
$fileName = "C:\code\employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName);
$newXmlEmployee = $xmlDoc.employees.AppendChild($xmlDoc.CreateElement("employee"));
$newXmlEmployee.SetAttribute("name","Pam");
$newXmlEmployee.SetAttribute("id","e1003");
$newXmlEmployee.SetAttribute("department","reception");
$xmlDoc.Save($fileName);
但是我跟以下錯誤消息映入眼簾:
You cannot call a method on a null-valued expression. At C:\code\testing.ps1:6 char:48 + $newXmlEmployee = $xmlDoc.employees.AppendChild <<<< ($xmlDoc.CreateElement("employee")); + CategoryInfo : InvalidOperation: (AppendChild:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression. At C:\code\testing.ps1:7 char:29 + $newXmlEmployee.SetAttribute <<<< ("name","Pam"); + CategoryInfo : InvalidOperation: (SetAttribute:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression. At C:\code\testing.ps1:8 char:29 + $newXmlEmployee.SetAttribute <<<< ("id","e1003"); + CategoryInfo : InvalidOperation: (SetAttribute:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression. At C:\code\testing.ps1:9 char:29 + $newXmlEmployee.SetAttribute <<<< ("department","reception"); + CategoryInfo : InvalidOperation: (SetAttribute:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
我將如何解決這個問題?
感謝@馬丁!現在我需要在僱員節點下添加一個子節點,我試過了:$ newXmlEmployee = $ xmlDoc.company.employees.employee.AppendChild($ xmlDoc.CreateElement(「address」));但我結束了這個錯誤: 方法調用失敗,因爲[System.Object []]不包含名爲'AppendChild'的方法 - 嵌套節點處理方式不同嗎? – pinkie
因爲有多個員工節點 - 你必須選擇一個你想創建一個孩子。請接受這個答案,並開始另一個問題,如果你沒有得到它的工作。 –