Home > Software engineering >  Powershell: How to update specific character of attribute value of XML node
Powershell: How to update specific character of attribute value of XML node

Time:12-03

I am new to exploring XML to Powershell.. I have here a sample XML that I need to edit the value.

Sample XML

<Configuration>
   <System>
      <Address link = "http://www.thispage.com" page = "first" />
      <Address link = "http://www.thispage.com" page = "second"/>
  </System>
</Configuration>

And here is my 'supposed to be result' when I edit the XML.

<Configuration>
   <System>
      <Address link = "https://www.thispage.com" page = "first" />
      <Address link = "https://www.thispage.com" page = "second"/>
  </System>
</Configuration>

I have tried this code:

$fileName = "C:\Project\XML-file\SampleXML.config"
$xmlContent = [xml](Get-Content $fileName)

$xmlContent | Select-Xml -XPath 'Configuration/system/Address' | ForEach-Object {$_.node.link -replace 'http','https'}
$xmlContent.save($fileName)

In this code, the value is not replaced, but file is being saved (No changes to the file).. But I can see in Powershell console that http is replaced with https

I also tried SetAttribute command, but it is replacing the whole value of link. Ex:

<Configuration>
   <System>
      <Address link = "https" page = "first" />
      <Address link = "https" page = "second"/>
  </System>
</Configuration>

Appreciate your inputs!

CodePudding user response:

Your xml is not closed properly with </Configuration>.

To load an xml, it is better to use below method then using $xmlContent = [xml](Get-Content $fileName), because the .Load() method makes sure you get the file encoding right.

Try

$fileName = "C:\Project\XML-file\SampleXML.config"
$xmlContent = New-Object -TypeName 'System.Xml.XmlDocument'
$xmlContent.Load($fileName)

$xmlContent.DocumentElement.System.ChildNodes | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
# or
# $xmlContent.Configuration.System.Address | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
# or
# $xmlContent.SelectNodes('//Address') | ForEach-Object { $_.SetAttribute('link', ($_.GetAttribute('link') -replace '^http:', 'https:')) }

$xmlContent.Save($fileName)
  • Related