Jinx
Jinx

Reputation: 43

replacing text in multiple elements in an XML file

I have multiple endpoints in an XML doc where I am trying to replace some of the address strings. I don't want to replace the same text in the entire doc just in the endpoints. So I have tried to narrow it down and tried different ways but I cannot get it to work.

This is my most recent attempt. Am I missing something incredibly obvious here?

$xmlDoc = [XML](Get-Content "$path\filename.exe.config")

foreach ($i in $xmlDoc.configuration.'system.serviceModel'.client.endpoint) {
  if ($i.address -match "bla") {
    $i.address -replace "bla", "foo"
  }
}

$xmlDoc.Save("$path\filename.exe.config")

Upvotes: 1

Views: 2045

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

What @PetSerAl is trying to tell you is that the -replace operator doesn't update the address nodes. You need to assign the modified value back to the node to actually change your XML data. Also, depending on the structure of your XML, dot-notation may not work for you (if a parent node contains several address nodes, $i would contain a list of these nodes). I'd recommend using SelectNodes() with an XPath expression to be on the safe side.

foreach ($addr in $xmlDoc.SelectNodes('/configuration/system.serviceModel/client/endpoint/address')) {
  $addr.'#text' = $addr.'#text' -replace 'bla', 'foo'
}

Upvotes: 2

Related Questions