How to change the value of XML Element attribute using PowerShell?

user3759904 picture user3759904 · Jul 10, 2014 · Viewed 50k times · Source

I am trying to access and change the particular attribute from XML tag

XML:

<office>
  <staff branch="Hanover" Type="sales">
    <employee>
        <Name>Tobias Weltner</Name>
        <function>management</function>
        <age>39</age>
    </employee>
    <employee>
        <Name>Cofi Heidecke</Name>
        <function>security</function>
        <age>4</age>
    </employee>
  </staff>
  <staff branch="London" Type="Technology">
   <employee>
    <Name>XXXX</Name>
    <function>gement</function>
    <age>39</age>

From the above example I want to print branch attribute and then want to change it with one value such as New York in all the whole XML and using below code to do that

       $xml=New-Object XML

      $xml.Load("C:\FE6Work.xml")

      $node=$xml.SelectNodes("/office/staff")

      write-output $node.branch
      $node.branch="New York"

But get an error stating can't find the element.

Can someone please help?

Answer

PeterK picture PeterK · Jul 10, 2014

Try the following:

$nodes = $xml.SelectNodes("/office/staff");
foreach($node in $nodes) {
    $node.SetAttribute("branch", "New York");
}

This will iterate through all nodes returned by SelectNodes() and modify each one.