Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

Change XML Value of element with specific Attribute in Powershell

i just can't wrap my head around XML so please help me.

i have following small xml file

<OSDCollBuild>
  <Group Name="OSD">
    <Value key="1">1809</Value>
    <Value key="2">1909</Value>
    <Value key="3">1909.1</Value>
    <Value key="4">20H2</Value>
  </Group>
  <Group Name="Office">
    <Value key="1">Standard</Value>
    <Value key="2">Professional</Value>
    <Value key="3">Student</Value>
  </Group>
</OSDCollBuild>

now i want to change the Value of e.g. Group Name=OSD Value key=3 to lets say "1909.2"

but i do not how to tell Powerhsell to set inner text to THAT specific Element. i have tryed to SelectSingleNode and i get thet far

$xml.OSDCollBuild.Group.SelectSingleNode("//*[@Name='$Group'])

and now i don't now how to get further.

question from:https://stackoverflow.com/questions/65918192/change-xml-value-of-element-with-specific-attribute-in-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the following xPath to get the node with Group Name=OSD Value key=3:

//OSDCollBuild/Group[@Name='OSD']/Value[@key='3']

Here is a full example to change the text value:

$xml = [xml]@"
<OSDCollBuild>
  <Group Name="OSD">
    <Value key="1">1809</Value>
    <Value key="2">1909</Value>
    <Value key="3">1909.1</Value>
    <Value key="4">20H2</Value>
  </Group>
  <Group Name="Office">
    <Value key="1">Standard</Value>
    <Value key="2">Professional</Value>
    <Value key="3">Student</Value>
  </Group>
</OSDCollBuild>
"@

# find the node to change
$node = $xml.SelectSingleNode("//OSDCollBuild/Group[@Name='OSD']/Value[@key='3']")

# change the value
$node.InnerText = "1909.2"

# dump the xml to verify the change
$xml.OuterXml

Output:

<OSDCollBuild>
    <Group Name="OSD">
        <Value key="1">1809</Value>
        <Value key="2">1909</Value>
        <Value key="3">1909.2</Value>
        <Value key="4">20H2</Value>
    </Group>
    <Group Name="Office">
        <Value key="1">Standard</Value>
        <Value key="2">Professional</Value>
        <Value key="3">Student</Value>
    </Group>
</OSDCollBuild>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...