Created
August 14, 2026 15:55
-
-
Save peteraritchie/3eefa8fdf5e814ef8063b55fac3e8633 to your computer and use it in GitHub Desktop.
A PowerShell script to add an XML element to a specified XPath in an XML file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Adds an XML element to a specified XPath in an XML file. | |
| .DESCRIPTION | |
| This script reads an XML file, adds a specified XML element to a given XPath within that file. | |
| It can optionally overwrite existing elements if the -Force parameter is specified. | |
| .PARAMETER Path | |
| The path to the XML file. | |
| .PARAMETER XPath | |
| The XPath to the target node where the new element will be added. | |
| .PARAMETER XmlText | |
| The XML text of the element to add. | |
| .PARAMETER Force | |
| If specified, existing elements with the same name will be overwritten. | |
| .EXAMPLE | |
| Add-XmlElement.ps1 .\test-project.csproj /Project/PropertyGroup "<UseVSTest>False</UseVSTest>" | |
| #> | |
| param( | |
| [Parameter(Mandatory=$true, Position=0)] | |
| [string]$Path, | |
| [Parameter(Mandatory=$true, Position=1)] | |
| [string]$XPath, | |
| [Parameter(Mandatory=$true, Position=2)] | |
| [string]$XmlText, | |
| [Parameter(Mandatory=$false)] | |
| [boolean]$Force = $false | |
| ) | |
| # Load the XML file | |
| [xml]$xml = Get-Content -Path $Path -Raw | |
| # Find the target node | |
| $targetNode = $xml.SelectSingleNode($XPath) | |
| [xml]$fragment = "<root>$XmlText</root>" | |
| foreach ($child in $fragment.DocumentElement.ChildNodes) { | |
| if ($Force -or -not $targetNode.SelectSingleNode($child.Name)) { | |
| $importNode = $xml.ImportNode($child, $true) | |
| $targetNode.AppendChild($importNode) | Out-Null | |
| } else { | |
| Write-Verbose "The element '$($child.Name)' already exists at path '$XPath'. Use -Force to overwrite." | |
| } | |
| } | |
| if($false){ | |
| $importNode = $xml.ImportNode($fragment.DocumentElement.FirstChild, $true) | |
| if ($targetNode) { | |
| Write-Verbose "Adding XML element to path '$XPath' in file '$Path'"; | |
| # Replace the existing node | |
| $targetNode.AppendChild($importNode) | Out-Null | |
| } else { | |
| Write-Error "The path '$XPath' did not find an element in the XML document." | |
| $global:LASTEXITCODE = 1 ; | |
| return; | |
| } | |
| } | |
| # Save the updated file | |
| # $xml.Save($Path) | |
| [System.Xml.Linq.XDocument]::Parse($xml.OuterXml).ToString(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment