joshua davidson
joshua davidson

Reputation: 47

Finding a string and replace part of string within XML

I have got a xml file and would like to if part of a line in the xml matches a string replace part of that line of xml. I do believe it is probabily pretty simple but really cannot work out how to do it. Below I am showing a very small snippet of the XML but it should be enough to understand wht I am trying to do

<?xml version="1.0" encoding="utf-8"?>
<Server ObjId="SERVER01" Version="1123" AreaOfResponsibility="Area2" AreaCode="ODA">
  <SubSystems>
    <SubSystem ObjId="SS001" IPAddressA="192.168.103.16" IPAPort="0" IPAddressB="192.168.103.16" IPBPort="0">

What I want to do is when ObjId="SS001" replace IPAPort="0" with IPAPort="2115" in the XML and save it. Intially the way I was doing it was by hardcoding as seen below and this just is not scalable. What I would like is for when ObjId="" = a variable replace IPAPort="0" with IPAPort="$AnotherVariable" but without having to have the long replace parameters I currently have

[XML]$Con = Get-Content Path\To\XML
$Con | % { $_.Replace('ObjId="SS001" IPAddressA="192.168.103.16" IPAPort="0" IPAddressB="192.168.103.16" IPBPort="0"', 'ObjId="SS001" IPAddressA="192.168.103.16" IPAPort="2115" IPAddressB="192.168.103.16" IPBPort="0"')} | Set-Content $MT700XMLPath

Basically I just want a neater way of writing this

Upvotes: 2

Views: 52

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Use XPath to locate the relevant node(s), then modify them and save the [xml] doc:

$file = Get-Item Path\to\file.xml
[xml]$con = $file |Get-Content

# Discover relevant nodes with xpath query
foreach($node in $con.SelectNodes('//SubSystem[@ObjId="SS001"]')){
  # update the IPAPort attribtue value
  $node.SetAttribute('IPAPort', '2115')
}

# save document
$con.Save($file.FullName)

Upvotes: 5

Related Questions