How do you Modify a node name?

Hi, sorry to keep banging on about xml, but theres only one way to learn :D.
If I had

<User2>
some more xml
</User2>

How would i go about changing User2 to something else like User1.  Is there something that replace it or will i have to just read all the information into a NEW node.

Many thanks

Phil Winder


Answer this question

How do you Modify a node name?

  • SKMurthy

    The name property on the node is readonly, so I think you'd have to append all the child nodes into your new node, then replace the existing one.

    Example:


    // Replacing <user2> with <user1>
    XmlDocument doc = new XmlDocument();
    ...
    XmlNode user2Node = doc.SelectSingleNode("user2");
    XmlNode user1Node = doc.CreateElement("user1");
    foreach(XmlNode childNode in user2Node.ChildNodes)
    {
       user1Node.AppendChild(childNode);
    }

    // if you have attributes, you'll need this loop too
    foreach(XmlAttribute attribute in user2Node.Attributes)
    {
       // you have to clone the attribute, it seems to mess with user2Node.Attributes collection
       user1Node.Attributes.Append((XmlAttribute)attribute.Clone());
    }
    doc.ReplaceChild(user1Node, user2Node);

     



  • Jason Shave

    If you care about how it handles namespaces, then you might want to use this version which allows you to actually change the namespace of an element, as well as it's name.

    void RenameNode(XmlNode node, string prefix, string name, string nsuri) {
        XmlDocument doc = node.OwnerDocument;
        XmlNode newNode = doc.CreateElement(prefix, name, nsuri);
        XmlAttributeCollection attributes = node.Attributes;
        XmlAttributeCollection newAttributes = newNode.Attributes;
        while (attributes.Count > 0) {
            XmlAttribute a = attributes[0];
            if (a.LocalName == "xmlns" && a.Value == node.NamespaceURI) {
                // Strip out any namespace declarations that no longer apply.
                attributes.RemoveAt(0);
            }
    else {
                newAttributes.Append(a);
           
        }
        while (node.HasChildNodes){
            newNode.AppendChild(node.FirstChild);
        }
        node.ParentNode.ReplaceChild(newNode, node);
    }


  • Manjax

    Thats excelent.  I thought so. 

    Thanks for the code.  Very efficient, I did pretty much the same but with little elegance. 

    Many thanks

    Phil Winder

  • How do you Modify a node name?