0

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!

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I have edited the closing of xml with correct </Configuration>. Thanks for the input, I have tried your advice, it works to me.
@Mariyah Thanks for letting me know. If you find my answer solved your problem, please mark it as'done' by clicking the large checkmark icon on the left. This will help others with a similar question finding it more easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.