Powershell:将子节点添加到XML

时间:2016-07-04 05:38:37

标签: 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>

我正在尝试添加名为Pam的新员工,id =&#34; e1003&#34;在部门=&#34;接待&#34;。

这是我迄今为止所尝试过的:

$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);

但是,我接到以下错误消息:

  

您无法在空值表达式上调用方法。在   C:\ code \ testing.ps1:6 char:48   + $ newXmlEmployee = $ xmlDoc.employees.AppendChild&lt;&lt;&lt;&lt; ($ xmlDoc.CreateElement(&#34;雇员&#34));       + CategoryInfo:InvalidOperation:(AppendChild:String)[],RuntimeException       + FullyQualifiedErrorId:InvokeMethodOnNull

     

您无法在空值表达式上调用方法。在   C:\ code \ testing.ps1:7 char:29   + $ newXmlEmployee.SetAttribute&lt;&lt;&lt;&lt; (&#34;名称&#34;&#34;帕姆&#34);       + CategoryInfo:InvalidOperation:(SetAttribute:String)[],RuntimeException       + FullyQualifiedErrorId:InvokeMethodOnNull

     

您无法在空值表达式上调用方法。在   C:\ code \ testing.ps1:8 char:29   + $ newXmlEmployee.SetAttribute&lt;&lt;&lt;&lt; (&#34; ID&#34;&#34; E1003&#34);       + CategoryInfo:InvalidOperation:(SetAttribute:String)[],RuntimeException       + FullyQualifiedErrorId:InvokeMethodOnNull

     

您无法在空值表达式上调用方法。在   C:\ code \ testing.ps1:9 char:29   + $ newXmlEmployee.SetAttribute&lt;&lt;&lt;&lt; (&#34;部门&#34;&#34;接收&#34);       + CategoryInfo:InvalidOperation:(SetAttribute:String)[],RuntimeException       + FullyQualifiedErrorId:InvokeMethodOnNull

我如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你几乎得到了它。您刚刚错过了选择company的{​​{1}}节点:

employees

<强>输出:

$fileName = "C:\code\employees.xml";

$xmlDoc = [xml](Get-Content $fileName); 
$newXmlEmployee = $xmlDoc.company.employees.AppendChild($xmlDoc.CreateElement("employee"));
$newXmlEmployee.SetAttribute("name","Pam");
$newXmlEmployee.SetAttribute("id","e1003");
$newXmlEmployee.SetAttribute("department","reception"); 

$xmlDoc.Save($fileName);