Create And Add XML Element With Value - CSharp System.Xml

CSharp examples for System.Xml:XML Element

Description

Create And Add XML Element With Value

Demo Code


using System.Xml;
using System;//from www .  j a v  a  2s.  co m

public class Main{
        public static XmlElement CreateAndAddElementWithValue(XmlNode parentNode, string childName, string val)
      {
         XmlElement node;
         XmlDocument owner = null;
         if (parentNode.GetType() == typeof(XmlDocument))
            owner = (XmlDocument)parentNode;
         else
            owner = parentNode.OwnerDocument;
         node = owner.CreateElement(childName);

         parentNode.AppendChild(node);

         XmlAttribute attr = owner.CreateAttribute("value");
         attr.InnerText = val;
         node.Attributes.Append(attr);

         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