我有以下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>
<employee name="Pam" id="e1003" department="reception">
</employee>
</employees>
</company>
我想添加一个名为&#34; Address&#34;在每位员工和#34;地址&#34;下,添加名为&#34; HouseNumber&#34;,&#34; Street&#34;的不同孩子。和&#34; Zip&#34;
这是我到目前为止所尝试的,添加&#34;地址&#34;子:
$fileName = "C:\code\employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName);
$newXmlEmployee = $xmlDoc.company.employees.employee.AppendChild($xmlDoc.CreateElement("address"))
$xmlDoc.Save($fileName);
但是,我接到以下错误消息:
方法调用失败,因为[System.Object []]不包含 方法名为&#39; AppendChild&#39;。在C:\ code \ testing.ps1:10 char:64 + $ newXmlAddress = $ xmlDoc.company.employees.employee.AppendChild&lt;&lt;&lt;&lt; ($ xmlDoc.CreateElement(&#34;地址&#34)); + CategoryInfo:InvalidOperation:(AppendChild:String)[],RuntimeException + FullyQualifiedErrorId:MethodNotFound
我如何解决这个问题?
答案 0 :(得分:0)
您必须迭代每个节点并为每个节点创建address
节点:
$fileName = "C:\code\employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName);
$xmlDoc.company.employees.employee | Foreach-Object {
$_.AppendChild($xmlDoc.CreateElement("address"))
}
$xmlDoc.Save($fileName);
<强>输出:强>
<company>
<employees>
<employee name="Dwight" id="e1000" department="sales">
<address />
</employee>
<employee name="Toby" id="e1001" department="hr">
<address />
</employee>
<employee name="Jim" id="e1002" department="sales">
<address />
</employee>
<employee name="Pam" id="e1003" department="reception">
<address />
</employee>
</employees>
</company>
如果您需要更多的子项,只需将AppendChild
的输出分配给变量并使用它来附加它们。