XmlAttribute::CloneNode Method (Boolean)

 

Creates a duplicate of this node.

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

public:
virtual XmlNode^ CloneNode(
	bool deep
) override

Parameters

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.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{

   //Create an XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->Load( "2elems.xml" );

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

   //Add the attribute to the first book.
   XmlElement^ currNode = dynamic_cast<XmlElement^>(doc->DocumentElement->FirstChild);
   currNode->SetAttributeNode( attr );

   //An attribute cannot be added to two different elements.  
   //You must clone the attribute and add it to the second book.
   XmlAttribute^ attr2;
   attr2 = dynamic_cast<XmlAttribute^>(attr->CloneNode( true ));
   currNode = dynamic_cast<XmlElement^>(doc->DocumentElement->LastChild);
   currNode->SetAttributeNode( attr2 );
   Console::WriteLine( "Display the modified XML...\r\n" );
   XmlTextWriter^ writer = gcnew XmlTextWriter( Console::Out );
   writer->Formatting = Formatting::Indented;
   doc->WriteContentTo( writer );
}

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


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

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