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.
source share