How To Rename An XML Node Using C# XmlDocument

 

I recently hit an issue where i needed to change the name of an XML node. It ended up being a lot more complicated than I had expected it to be. node.Name is a read only field, so you can’t take the simple route and rename it this way. Since you cannot rename the node, I had to create a new node and delete the old one. Not overly complex, but it is a little messy with the limitations of the XmlDocument that require references to the old document. I also wanted to make this solution reusable. Here is the solution I came up with to rename an xml node using C# XmlDocument.

I will start with the method and explain why it seems overcomplicated for a simple task. The first parameter is the doc that oldRoot belongs to. The reason this needs to be passed is because you cant create an XmlNode without an XmlDocument and if you want to add a node to a document, it needs to be created with that document. This is why doc needs to be passed over. The for loop will take all of the elements from the old node and add them to the new node. This will mean that there are now 2 nodes that have the exact same content, but one has the new name that you wanted to rename the node to.

Once the new node has all the data of the old node, you can append this new node to the document and then remove the old one. This is all that you need to do. There is no real need for a return type here. You have passed doc as a parameter, any changes made to this doc will be made on a global level. When the method completes the change will have been made to the doc that you passed to this method.

            public static void renameXMLNode(XmlDocument doc, XmlNode oldRoot, string newname)
            {
                XmlNode newRoot = doc.CreateElement(newname);

                foreach (XmlNode childNode in oldRoot.ChildNodes)
                {
                    newRoot.AppendChild(childNode.CloneNode(true));
                }
                XmlNode parent = oldRoot.ParentNode;
                parent.AppendChild(newRoot);
                parent.RemoveChild(oldRoot);
            }

Here is a simple scenario where you could call this method.

XmlDocument doc = new XmlDocument();
doc.Load("c:/xmlfile.xml");

var items = doc.SelectSingleNode("//Rows");
XmlNodeList rowlist = items.ChildNodes;

for (int i = 0; i <= rowlist.Count-1; i++)
{
    Helpers.renameXMLNode(doc, itemlist[0], "itemRow");
}

 

Related Articles

Related Questions

Is My NVME Drive Unresponsive Due to a Cheap Adapter or Is It Actually Damaged?

I recently got a friend's NVME drive back from Dell after they said it couldn't be repaired. I tried to transfer the data using...

How can I factory reset my locked Android tablet?

Hey, I need some help! I recently bought a super budget Android Go tablet for just $3, but it's passcode locked. When I try...

Bent Pins on My Ryzen 5 5600X – Am I Out of Luck?

I recently purchased a used Ryzen 5 5600X to upgrade my PC, but while showing it to my wife, I accidentally inserted it upside...

2 COMMENTS

  1. This code does not only rename the element, but always moves it down to become the last sibling. This will likely invalidate your xml document against its schema, if the child elements are in a sequence.
    This would be solved if your replaced
    parent.AppendChild(newRoot);
    by
    parent.InsertBefore(newRoot, oldRoot);

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Latest Tools

Scavenger Hunt Team Randomizer

Planning a scavenger hunt and need to split participants into random teams? Whether you're organizing a school activity, a corporate team-building event, or a...

File Hash Generator Online – Get Instant MD5 and SHA-256 Hashes

Whether you are validating downloads, checking for corruption, or comparing files for duplicates, having a fast and secure way to generate file hashes is...

Visual CSS Editor for Modern Glass UI Effects

Modern UI design is all about clean, layered aesthetics, and few styles deliver this better than glassmorphism. If you're designing sleek user interfaces and...

Fast and Accurate Tap BPM Counter – Free Web Tool

Whether you're producing music, DJing live, or just figuring out the tempo of a song, knowing the BPM (beats per minute) can be critical....

Glassmorphism CSS Generator with Live Preview

Glassmorphism is one of the most visually striking design trends in modern UI. Its soft, frosted-glass effect adds depth and elegance to web interfaces,...

Add Custom Speech and Caption Boxes to Any Image Online

Creating comic-style images used to require complex design tools or specialist software. Whether you're making memes, teaching graphics, social media posts or lighthearted content,...

Latest Posts

Latest Questions