Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created May 18, 2012 18:44
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jpoehls/2726969 to your computer and use it in GitHub Desktop.
Save jpoehls/2726969 to your computer and use it in GitHub Desktop.
Use XPath to update XML using PowerShell
function Edit-XmlNodes {
param (
[xml] $doc = $(throw "doc is a required parameter"),
[string] $xpath = $(throw "xpath is a required parameter"),
[string] $value = $(throw "value is a required parameter"),
[bool] $condition = $true
)
if ($condition -eq $true) {
$nodes = $doc.SelectNodes($xpath)
foreach ($node in $nodes) {
if ($node -ne $null) {
if ($node.NodeType -eq "Element") {
$node.InnerXml = $value
}
else {
$node.Value = $value
}
}
}
}
}
$xml = [xml](Get-Content "c:\my\file.xml")
# <file><foo attribute="bar" attribute2="bar" attribute3="bar" /></file>
Edit-XmlNodes $xml -xpath "/file/foo[@attribute='bar']/@attribute" -value "new value"
$xml.save("c:\my\file.xml")
# <file><foo attribute="new value" attribute2="bar" attribute3="bar" /></file>
@sheldonhull
Copy link

great help to me, thanks for sharing this

@discoaaron
Copy link

Worked well for me, cheers!

@mattduguid
Copy link

mattduguid commented Aug 28, 2017

Nice work 👍 once we had our xPath query sorted this code helped replace the chunk of xml we were targeting :)

@andzi
Copy link

andzi commented Jun 24, 2018

Nice work thanks for sharing this

@gvdm90
Copy link

gvdm90 commented Jan 24, 2019

Great, it helped me a lot!

@florea-g
Copy link

Cool

@guillemsola
Copy link

Better than copilot 🤣

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment