Create And Add XML Element - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Create And Add XML Element

Demo Code


using System.Xml;
using System;//from ww  w . java  2s.  co m

public class Main{
    public static XmlElement CreateAndAddElement(XmlNode parentNode, string childName)
      {
         XmlElement node;
         if (parentNode.GetType() == typeof(XmlDocument))
            node = ((XmlDocument)parentNode).CreateElement(childName);
         else
            node = parentNode.OwnerDocument.CreateElement(childName);
         parentNode.AppendChild(node);
         return node;
      }
        /// <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