How to rename an XML node using PowerShell?

I am trying to rename an XML node using PowerShell. For instance:
<configuration>
<desktops>
<name>PC001</name>
<domain>CORP</domain>
</desktops>
<laptops>
<name>PC002</name>
<domain>CORP</domain>
</laptops>
</configuration>

I want to rename the first <name> tags to <PC1name> (and </PC1name> respectively). Here is what I have so far:

$InputFile = "NetworkConfigs.xml"
$xml = [xml](get-content $InputFile)
$root = $xml.get_DocumentElement();
#replace the node
$ root.desktops.name.? `

$xml.Save($InputFile)

I don’t know how to replace the tag with something else. Tips?

+4
source share
3 answers

Bottom line, XML node name unchanged. Link msdn .

Here is a brief example of creating a new node with the required data. Hope it helps.

 $InputText = @" <configuration> <desktops> <name>PC001</name> <domain>CORP</domain> </desktops> <laptops> <name>PC002</name> <domain>CORP</domain> </laptops> </configuration> "@ $xml = [xml]($inputText) $desktopsNode = [System.Xml.XmlElement]$xml.configuration.desktops $nameNode = $desktopsNode.SelectSingleNode('name') $pcNameNode = $xml.CreateElement('PC1Name') $pcNameNode.InnerText = $nameNode.InnerText [void]$desktopsNode.AppendChild($pcNameNode) [void]$desktopsNode.RemoveChild($nameNode) $xml.OuterXML 

Output:

 <configuration><desktops><domain>CORP</domain><PC1Name>PC001</PC1Name></desktops><laptops><name>PC002</n ame><domain>CORP</domain></laptops></configuration> 
+6
source

Renaming nodes in XML is more complicated than you might expect. This is especially bad if the node is the root of the node or the parent with a complex hierarchy of child nodes. Most of the β€œrenaming” methods I've seen will clone children and add them to the new node. This process is a little simplified if your API also includes a ReplaceChild method. (I can provide details if you need them.)

An alternative method that I used (especially if XML can be represented as a string) is to replace the text in XML before converting it to an XmlDocument.

 $InputText = @" <configuration> <desktops> <name>PC001</name> <domain>CORP</domain> </desktops> <laptops> <name>PC002</name> <domain>CORP</domain> </laptops> </configuration> "@ $regex = [regex]'(</?)name>' $ModifiedText = $regex.Replace($InputText,"`$1PC1Name>",2) $xml = [xml]$ModifiedText 

Note that the replace statement finds and fixes the first two occurrences of a match - only the open and close tag of the first element. Delete the number to find and replace all occurrences in the string. Also note that the regular expression captures the opening tag tags, so that they can be inserted into the match string as $ 1.

+2
source
 $oldtag = "name" $newtag = "PC1name" $xml = Get-Content D:\oldfile.xml $new = $xml -replace $oldtag, $newtag Set-content -path D:\newfile.xml -value $new 

My way is to convert the XML to a string, and then replace the node (which in this case is a regular string). It works for me.

0
source

All Articles