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

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


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.


You can access the attributes directly in the [xml] object like this:

# C:\temp> $xml = [xml](Get-Content C:\FE6Work.xml)# C:\temp> $xml.office.staffbranch                   Type                           employee                                                             ------                   ----                           --------                                                             Hanover                  sales                          {Tobias Weltner, Cofi Heidecke}                                      London                   Technology                     {XXXX, Cofi}                                                         # C:\temp> $xml.office.staff | foreach{$_.branch = "New York"}# C:\temp> $xml.office.staffbranch                   Type                           employee                                                             ------                   ----                           --------                                                             New York                 sales                          {Tobias Weltner, Cofi Heidecke}                                      New York                 Technology                     {XXXX, Cofi}                                                         


if we are taking attribute from console and changing its value ?

$path=Read-Host -Prompt 'Enter path of xml file'[xml]$xmldata = get-content "$path"$tag = Read-Host -Prompt 'Enter tag'$value = Read-Host -Prompt 'Enter value'$xmldata.InstallConfig.$tag="$value"$xmldata.Save($path)