XmlAttribute.CloneNode Method (Boolean)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Creates a duplicate of this node.

Namespace:   System.Xml
Assembly:  System.Xml (in System.Xml.dll)

public override XmlNode CloneNode(
	bool deep


Type: System.Boolean

true to recursively clone the subtree under the specified node; false to clone only the node itself

Return Value

Type: System.Xml.XmlNode

The duplicate node.

This method serves as a copy constructor for nodes. The cloned node has no parent (ParentNode returns null).

Cloning an unspecified attribute returns a specified attribute (Specified returns true).

The following example uses CloneNode to add an attribute to two different element nodes.

using System;
using System.IO;
using System.Xml;

public class Sample
  public static void Main()
    //Create an XmlDocument.
    XmlDocument doc = new XmlDocument();

    //Create an attribute.
    XmlAttribute attr;
    attr = doc.CreateAttribute("bk","genre","urn:samples");
    attr.Value = "novel";

    //Add the attribute to the first book.
    XmlElement currNode = (XmlElement) doc.DocumentElement.FirstChild;

    //An attribute cannot be added to two different elements.  
    //You must clone the attribute and add it to the second book.
    XmlAttribute attr2;
    attr2 = (XmlAttribute) attr.CloneNode(true);
    currNode = (XmlElement) doc.DocumentElement.LastChild;

    Console.WriteLine("Display the modified XML...\r\n");
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;


The example uses the file, 2elems.xml, as input.

<!--sample XML fragment-->
  <book ISBN='10-861003-324'>
    <title>The Handmaid's Tale</title>
  <book ISBN='1-861001-57-5'>
    <title>Pride And Prejudice</title>

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top