PowerShell function to edit nodes in an XML file.
function Edit-XmlNodes
{
param(
[xml] $doc,
[string] $xpath = $(throw "xpath is a required parameter"),
[string] $value = $(throw "value is a required parameter")
)
$nodes = $doc.SelectNodes($xpath)
$count = $nodes.Count
Write-Verbose "Found '$count' nodes with path '$xpath'."
foreach ($node in $nodes)
{
if ($node -ne $null)
{
if ($node.NodeType -eq "Element")
{
$node.InnerXml = $value
}
else
{
$node.Value = $value
}
}
}
}
#
# Example Usage:
#
$xml = New-Object System.Xml.XmlDocument
$xml.Load($nuspecPath)
Edit-XmlNodes -doc $xml -xpath "//*[local-name() = 'id']" -value $packageId
Edit-XmlNodes -doc $xml -xpath "//*[local-name() = 'version']" -value $nugetVersion
$depNodes=$xml.SelectNodes("/package/metadata/dependencies/group/dependency")
foreach ($depNode in $depNodes)
{
$dependencyId = $depNode.id;
Write-Verbose $dependencyId
if ($dependencyId -eq "Hl7.Fhir.DSTU2")
{
Write-Host "Replacing dependency version for '$dependencyId' with '$nugetVersion'."
$depNode.version = $nugetVersion
}
}
Write-Verbose $xml.OuterXml
$xml.save($nuspecPath)