pinkie
pinkie

Reputation: 25

Powershell: add child node to XML

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>
  </employees>
</company>

And I'm trying to add a new employee named Pam, id="e1003" under department="reception".

This is what I've tried so far:

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

However I'm greeted with the following error messages:

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

How would I resolve this?

Upvotes: 1

Views: 1367

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

You almost got it. You just missed the company node where you select the 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);

Output:

<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" />
  </employees>
</company>

Upvotes: 0

Related Questions