简体   繁体   中英

Powershell - read and exchange node value within XML

I would like to read following node and set a new value. Due to two existing same nodes with different ID's I'm quite not able to change a sub value.

Here's an example: XML Source:

    <root>
      <node1>
            <child>
                 <baby>
                  <id>1</id>
                  <targetvalue>9999</targetvalue>
                 </baby>

                <baby>
                 <id>2</id>
                 <targetvalue>9999</targetvalue>
                </baby>
             </child>
      </node1>
</root>




if (($myXML.root.node1.child.baby | Where-Object {$_.id -eq '1'-and $_.targetvalue -eq '9999'}) -ne $null) {
"TEST"}

I tried it already via get-content, but due to two ids I'm not able to modify at least one value. May someone please help? :)

I think this is what you're after...

This sets the baby node you want to modify:

$babyNode = ($myXML.root.node1.child.baby | Where-Object {$_.id -eq '1'-and $_.targetvalue -eq '9999'})

This modifies the value:

$babyNode.targetvalue = "TEST"

And this shows both baby nodes, one with the updated value:

$myXML.root.node1.child.baby

I would say: use right tool for the job. As you are working with XML - Select-Xml (and XPath) should be your first choice:

$node = Select-Xml -Path Path\To\Original.xml -XPath "//baby[id = '1']"
$node.Node.targetvalue = '444'
$node.Node.OwnerDocument.Save('c:\temp\Modified.xml')

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