Rename XML Node - CSharp System.Xml

CSharp examples for System.Xml:XML Node

Description

Rename XML Node

Demo Code


using System.Xml;
using System;/*  ww w  .  j av a2 s.co  m*/

public class Main{
        public static XmlNode RenameNode(XmlNode node, string sNewName)
      {
         //can't just change the name of an XML node, so we have to create new, copy stuff and replace.
         XmlNode newNode = node.OwnerDocument.CreateNode(node.NodeType, sNewName, null);
         newNode.InnerXml = node.InnerXml;
         foreach (XmlAttribute attrib in node.Attributes)
         {
            XmlAttribute newAttrib = (XmlAttribute)node.OwnerDocument.CreateNode(XmlNodeType.Attribute, attrib.Name, null);
            newAttrib.InnerText = attrib.InnerText;
            newNode.Attributes.Append(newAttrib);
         }
         XmlNode parentNode = node.ParentNode;
         XmlNode insertBeforeNode = node.NextSibling;
         parentNode.RemoveChild(node);
         if (insertBeforeNode == null)
            parentNode.AppendChild(newNode);
         else
            parentNode.InsertBefore(newNode, insertBeforeNode);
         //parentNode.ReplaceChild(newNode, node);
         return newNode;
      }
        /// <summary>
        /// Unlike XmlNode.AppendChild(), this one works regardless of if they have the same OwnerDocument or not. Unless there's a Scheme
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="childNode"></param>
        public static void AppendChild(XmlNode parentNode, XmlNode childNode)
        {
            if (parentNode.OwnerDocument == childNode.OwnerDocument)
                parentNode.AppendChild(childNode);
            else
            {
                XmlNode newChildNode = parentNode.OwnerDocument.CreateNode(childNode.NodeType, childNode.Name, null);
                parentNode.AppendChild(newChildNode);
                if (childNode.InnerText.Length > 0)
                    newChildNode.InnerText = childNode.InnerText;

                foreach (XmlAttribute attribute in childNode.Attributes)
                {
                    CreateAndAddAttribute(newChildNode, attribute.Name, attribute.InnerText);
                }

                foreach (XmlNode node in childNode.ChildNodes)
                {
                    AppendChild(newChildNode, node);
                }
            }
        }
}

Related Tutorials