1

I need to update one line in xml and save changes. It looks ease but it doesn't work for me and I cannot find my mistake ( So, I need help. It is my code:

[xml]$XmlDocument = Get-Content -Path "C:\Users\Administrator\Documents\Practise\Test.xml"
$random = -join ((48..57) + (97..122) | Get-Random -Count 16 | % {[char]$_})

$node = $XmlDocument.Payment.PaymentOptions.Bank.Value5
$node = $node.Replace('13384wL839', $random)

$XmlDocument.Save("C:\Users\Administrator\Documents\Practise\Test.xml")

there is my xml:

<Payment xmlns="2.0.0">
  <PaymentValue1>
    <value1>180.00</value1>
    <value2>2017-09-30</value2>
    <value3>022456789</value3>
  </PaymentValue1>
  <PaymentOptions>
    <Bank>
      <Value4>Test1</Value4>
      <Value5>13384wL839</Value5>
    </Bank>
  </PaymentOptions>
</Payment>

I see that $node is changed but when I save new xml - it is still old value is displayed.

2 Answers2

1

Since the new value isn't related to the old one,
there is no need to replace anything,
you simply set the value.

$File= "C:\Users\Administrator\Documents\Practise\Test.xml"
[xml]$XmlDocument = Get-Content $File
$random = -join ((48..57) + (97..122) | Get-Random -Count 16 | % {[char]$_})

$XmlDocument.Payment.PaymentOptions.Bank.Value5 = $random

$XmlDocument.Save($File)
0

You are never actually setting the value back into the document.

$XmlDocument.Payment.PaymentOptions.Bank.Value5 = $XmlDocument.Payment.PaymentOptions.Bank.Value5.Replace('13384wL839', $random)

Should do the trick.

BlythMeister
  • 299
  • 1
  • 12