Skip to main content

How to rename an XML Node in C#


This was driving me crazy - here's an easy cut and paste solution to not being able to use the DOM to rename a node for lazy developers like me:

public static XmlNode RenameNode (XmlNode node, string namespaceURI,string qualifiedName)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement oldElement = (XmlElement) node;
XmlElement newElement =
node.OwnerDocument.CreateElement(qualifiedName, namespaceURI);

while (oldElement.HasAttributes)
{
newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0]));
}

while (oldElement.HasChildNodes)
{
newElement.AppendChild(oldElement.FirstChild);
}

if (oldElement.ParentNode != null)
{
oldElement.ParentNode.ReplaceChild(newElement, oldElement);
}

return newElement;
}
else
{
return null;
}
}

Ahh. That's better :)

Comments

  1. Just saw your post too late and developed my own solution!

    The following works given that you are iterating over some of the nodes in the document, and have stored them in an ArrayList of XmlNode's called 'oldNodes'. I had to use indexed access to the ArrayList rather than iteration (with a foreach), as the latter had 'unexpected' results!


    for(int i=0; i < oldNodes.Count; i++)
    {
    XmlDocumentFragment f = doc.CreateDocumentFragment();
    XmlNode old = oldNodes[i] as XmlNode;
    f.InnerXml = old.OuterXml.Replace(old.Name, newName);
    old.ParentNode.ReplaceChild(f.ChildNodes[0], old);
    }

    Eoghan http://eoghan.qatano.org/

    ReplyDelete
  2. Anonymous7:12 am

    Great piece of reusable code. Saved me some time. Thanks!!

    ReplyDelete
  3. Stiefel12:34 am

    Sorry Eoghan, but i think your code fails if the tag-name is used in some child node again -> in this case all tags are renamed ..

    ReplyDelete
  4. Anonymous10:14 am

    Just noticed that you posted this in 2006...well, it still works great in 2011! Thanks!

    ReplyDelete
  5. Anonymous11:03 pm

    public static XmlNode RenameNode (XmlNode node, string namespaceURI,string qualifiedName)
    {
    if (node.NodeType == XmlNodeType.Element)
    {
    XmlElement oldElement = (XmlElement) node;
    XmlElement newElement =
    node.OwnerDocument.CreateElement(qualifiedName, namespaceURI);

    while (oldElement.HasAttributes)
    {
    newElement.SetAttributeNode(oldElement.RemoveAttributeNode(oldElement.Attributes[0]));
    }

    while (oldElement.HasChildNodes)
    {
    newElement.AppendChild(oldElement.FirstChild);
    }

    if (oldElement.ParentNode != null)
    {
    oldElement.ParentNode.ReplaceChild(newElement, oldElement);
    }

    return newElement;
    }
    else
    {
    return null;
    }
    }

    ReplyDelete
  6. 3 issues:

    1. Signature should be changed to
    public static XmlNode RenameNode (this XmlElement node, string namespaceURI,string qualifiedName)

    this allow 1, remove the unncessery check, and use the code as extention method for XmlElements

    myElement.RenameNode("newName");


    2. there is a problem with references kept to the old node, which are NOT updated


    3. this is a very lengthy operation which traverse a lot of items (possibly) so use it only when REAALLY necessery.


    Other then that, Kudos.
    nice work.

    ReplyDelete
  7. Anonymous4:04 pm

    What if the oldElement has no parent node, i.e renaming an XmlElement directly under the XmlDocument as DocumentElement?

    ReplyDelete

Post a Comment

Popular posts from this blog

Considerably smaller than Texas...

Well, after jonron 's nagging, I figured I better post something! It's weird - being so far away from home and in such a strange foreign place - you'd think that I'd have all kinds of things to say, but in truth most of the time I'm either so busy with work that I don't have time to post, or so lonely that I don't want to burden you all with my misery... (sob!) Anyway - I'm currently posting from the Best Western Hotel in Corpus Christi, Texas . (We have a TRIM Customer here who needs some help with configuring their records management system, so Simon and I have been helping out. ) I'm not sure that I'd ever want to stay at the Worst Western. Or even the Average Western, but no matter... Texas has been a pretty entertaining place to visit. Our efforts at finding a place to park ended in a church parking lot where the sign said "Clergy Only - Sinners Will be Prosecuted (and towed)" When we finally found the office, there was another gi...

Going West vs Going to Sleep

Phew! That was one busy adventure to the other side of this wide brown land (It is wide, and brown, but mainly wide) TUF 2005 in Perth was the launching ground for our new product, ice. Stilly and I were presenting the keynote, which was based around showing off ice, and talking about collaboration and other reasons why a bunch of customers might want to buy it. In a stroke of genius\insanity, we decided to let the audience pick the demonstration platform based on random outcomes - we built a giant cardboard die with various operating systems and platforms written on each side - then we'd let a volunteer from the audience roll the dice(die?) to determine which platform we should do our demo on. ice (the italics belong to the marketing department) works on any platform, so we were pretty confident that we would be okay. But, what I hadn't counted on (those italics are mine), was my crummy laptop (which was acting as the server) deciding that it would be a good idea to hibernat...

Dreams of a night on the TRIM

Disclaimer:People's dreams are often not very interesting to anyone but them. But this was so weird I had to write it down. I don't know what it means, other than to highlight the fact that I'm a little deranged. All companies and people in this dream are actually me, and almost definitely wouldn't behave in such a fashion in real life. No correspondence will be entered into. Shimmery Dissolve in In my dream, software was alcohol . Everybody was drunk all the time, because of the amount of software in the work place. Big companies like Microsoft and Oracle were in the business of getting people shitfaced at big conventions, where they'd teach you about the alcohol molecule and how they'd added a new hydroxide molecule. Microsoft called this directDrink. IBM had a reputation for taking out the CEOs of large enterprises and getting them all really drunk, thus mandating more IBM liquor (which was blue) be bought and drunk by millions of government employees around ...