Here is a quick code snippet to Add a Node in XML from from the XPath, the following PowerShell function will search for the node hierarchy, if it does not exist then it will create it.
function CheckForXMLNode {
function CheckForXMLNode {
param (
$File, # File Path of XML to search the node
$NodePath
)
$nodes = $NodePath -split "/"
$path = "//Configuration"
# My Sample Node Path is like this
# //Configuration/Farm/CustomParent/CustomChild
foreach ($node in $nodes) {
if ( ($node -ne "") -and ($node -ne "Configuration") ) {
[xml]$xml = Get-Content $File
$PathToCheck = $path+"/"+$node
$NodeToCheck = $xml.SelectSingleNode($PathToCheck)
if(!$NodeToCheck){
Write-Host "$node Node does not existing. creating ...." -NoNewline
$NewNode = $xml.CreateElement($node)
$xml.SelectNodes($path).AppendChild($NewNode) | Out-Null
Write-Host "OK" -BackgroundColor Green -ForegroundColor Black
$xml.Save($File)
}
$path += "/$node"
}
}
}
Comments
Post a Comment