Merge Overwrite XmlNode - CSharp System.Xml

CSharp examples for System.Xml:XML Node

Description

Merge Overwrite XmlNode

Demo Code


using System.Xml;
using System;/*from   w w w  . j  ava  2  s. com*/

public class Main{
        public static void MergeOverwrite(XmlNode nodeDst, XmlNode nodeSrc)
      {
         foreach (XmlNode node in nodeSrc.ChildNodes)
         {
            XmlNode newNode = nodeDst[node.Name];
            if (newNode==null)
            {
               newNode = nodeDst.OwnerDocument.CreateNode(node.NodeType, node.Name, null);
               nodeDst.AppendChild(newNode);
            }
            newNode.InnerXml = node.InnerXml;
         }
      }
        /// <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