Home > Software engineering >  Change ChildNodes in xml file using Powershell
Change ChildNodes in xml file using Powershell

Time:11-08

I'm trying to change the value in xml.

XML file:

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <setting name="Attach" defaultValue="False" value="" />
  <setting name="Connections" defaultValue="" value="CHANGE_THE_VALUE" />
  <setting name="Destroy" defaultValue="True" value="" />
</settings>

I need to change the value in "Connections"

Powershell:

$file = "C:\New folder\UserSettings.xml"
$xmldata = [xml] (Get-Content $file)
$xmldata.settings.ChildNodes
$xmldata.Save((Resolve-Path $file).Path)

How should I modify the 3rd string in the code above?

CodePudding user response:

You can use the SelectSingleNode Method to find and update the node, then .Save as you're already doing:

$xml = [xml]::new()
$xml.Load('path\to\file.xml')
$xml.SelectSingleNode('/settings/setting[@name="Connections"]').Value = 'Hello World'
$xml.Save('path\to\file.xml')

CodePudding user response:

$xmldata.settings.ChildNodes | where {$_.name -eq "Connections"} | foreach {$_.value = "new-value"}

Then you can save the file as you did before. However, that saving method only works if the file already exists (which it does in your case since you are saving to the same file that you read from).

  • Related