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.

0

2 Answers 2

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

Comments

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.

9 Comments

I also tried to save value in new document. In this way new docuement is created but value doesn't update. $XmlDocument.Payment.PaymentOptions.Bank.Value5 = $XmlDocument.Payment.PaymentOptions.Bank.Value5.Replace('13384wL839', $random) -- it doesn't help. Value is changed but xml does not updated
Updated answer, there was an error. From blogs.msdn.microsoft.com/sonam_rastogi_blogs/2014/05/14/…
As I see current node doesn't have such properties as "Value", so replace doesn't work
Edited again, I think this is a duplicate though, so flagged accordingly
$XmlDocument.Payment.PaymentOptions.Bank.Value5 = $XmlDocument.Payment.PaymentOptions.Bank.Value5.Replace('13384wL839', $random) -- I made a mistake when tried this one. but I try again and it works! Thank you for help =)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.