micsea64
micsea64

Reputation: 109

Node selection and replacement

<XMLFile>
  <Pattern Pattern="1">
    <ID1>10</ID1>
    <ID2>2</ID2>
    <ID3>01_1</ID3>
    <ID4>01_1_SOTR_SOTR</ID4>
    <ID5>O</ID5>
   </Pattern>
</XMLFile>

I am trying to search an XML File for a set of conditions. In this situation, I am looking for ID1 = 10, and whenever I find an ID1 = 10, I need to change ID5 from a O to an L. (I also have a few hundred of these node blocks to change by the way).

So I can search for my condition with the following:

$_XMLFile = [xml] (Get-Content $_XMLFilePath)

$nodes = $_XMLFile.XMLFile.Pattern | % {$_.ID1 -eq '10'} |
         Select-Object -Property ID5

What I am having issue with is changing ID5, once I have that list of nodes.

I have tried

foreach ($node in $nodes) {
    $nodes | % {$_.ID5 -replace "O", "L"}
}

Upvotes: 0

Views: 27

Answers (1)

Alexander Drogin
Alexander Drogin

Reputation: 661

Why not using XPath to find the list of nodes?

$xmlDoc = New-Object -TypeName System.Xml.XMLDocument
$xmlDoc.Load($fileName)
[System.Xml.XmlNodeList]$nodeList = $xmlDoc.SelectNodes('XMLFile/Pattern[ID1=10]/ID5')
foreach ($node in $nodeList) {
    $node.'#text' = 'L'
}

$xmlDoc.Save($newFileName)

Upvotes: 1

Related Questions