Clone XML Element To Document - CSharp System.Xml

CSharp examples for System.Xml:XML Document

Description

Clone XML Element To Document

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Xml;
using System.Text;
using System.Security.Policy;
using System.Reflection;
using System.IO;/* ww w.j a v a  2  s. co  m*/
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;
using System.Collections;
using System;

public class Main{
        //NOTE: XmlDocument.ImportNode munges "xmlns:asmv2" to "xmlns:d1p1" for some reason, use XmlUtil.CloneElementToDocument instead
        public static XmlElement CloneElementToDocument(XmlElement element, XmlDocument document, string namespaceURI)
        {
            XmlElement newElement = document.CreateElement(element.Name, namespaceURI);
            foreach (XmlAttribute attribute in element.Attributes)
            {
                XmlAttribute newAttribute = document.CreateAttribute(attribute.Name);
                newAttribute.Value = attribute.Value;
                newElement.Attributes.Append(newAttribute);
            }
            foreach (XmlNode node in element.ChildNodes)
                if (node.NodeType == XmlNodeType.Element)
                {
                    XmlElement childElement = CloneElementToDocument((XmlElement)node, document, namespaceURI);
                    newElement.AppendChild(childElement);
                }
                else if (node.NodeType == XmlNodeType.Comment)
                {
                    XmlComment childComment = document.CreateComment(((XmlComment)node).Data);
                    newElement.AppendChild(childComment);
                }
            return newElement;
        }
}

Related Tutorials