简体   繁体   中英

Powershell - Updating XML Text under Count Node

I have an XML file that looks like this

<Transactions>
    <Transaction Type="Login">
        <LoginSetting>blahblah</LoginSetting>
    </Transaction>
    <Transaction Type="Search">
        <Parameters>blahblah</Parameters>
        <Count>Setting</Count>
    </Transaction>
    <Transaction Type="Logout">
        <LogoutSetting>blahblah</LogoutSetting>
    </Transaction>
</Transactions>

The path to this file is stored under $xml_path and using powershell I've imported those settings into [xml]$xml

[xml]$xml = (get-content $xml_path)

I'm trying to update the value under the "Count" node

$xml.Transactions.Transaction.Count = 'NewSetting'

Since .Count is something that can be run to get the number of nodes named "Transaction", powershell gives me this error output

'Count' is a ReadOnly property.

Is there another way to update the value under the "Count" node?

This was my workaround: I imported the xml data into two variables - One as Flat Text and the other as XML

$xml_flat = (get-content $xml_path)
[xml]$xml = (get-content $xml_path)

I pulled the value for "Count" from the xml variable (since it won't necessarily have a value of 'Setting' as displayed)

$count = Select-Xml -XML $xml -XPath "//Count"

I ran a .replace against the flat variable to update the setting I needed to.

$xml_flat = $xml_flat.replace("<Count>$count</Count>","<Count>NewSetting</Count>")

From there i was able to import $xml_flat into an xml variable as $xml_new and am able to do whatever else I need to

[xml]$xml_new = $xml_flat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM