Powershell: add child node in XML

2020-04-21 08:40发布

I have the following XML tree:

<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>

I would like to add a child named "Address" under each employee and under "Address", add different children named "HouseNumber", "Street" and "Zip"

This is what I've tried so far, to add the "Address" child:

$fileName = "C:\code\employees.xml";
$xmlDoc = [System.Xml.XmlDocument](Get-Content $fileName); 
$newXmlEmployee = $xmlDoc.company.employees.employee.AppendChild($xmlDoc.CreateElement("address"))
$xmlDoc.Save($fileName);

However I'm greeted with the following error messages:

Method invocation failed because [System.Object[]] doesn't contain a method named 'AppendChild'. At C:\code\testing.ps1:10 char:64 + $newXmlAddress = $xmlDoc.company.employees.employee.AppendChild <<<< ($xmlDoc.CreateElement("address")); + CategoryInfo : InvalidOperation: (AppendChild:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

How would I resolve this?

1条回答
Viruses.
2楼-- · 2020-04-21 09:09

You have to iterate over each node and create the address node for each of them:

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

Output:

<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>

If you need more subchildren, just assign the output of the AppendChild to a variable and use it to Append them.

查看更多
登录 后发表回答