Export (0) Print
Expand All

XmlAttribute.CloneNode Method

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>

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0
© 2015 Microsoft