XmlDocument.CloneNode(Boolean) 方法

定义

创建此节点的副本。

public:
 override System::Xml::XmlNode ^ CloneNode(bool deep);
public override System.Xml.XmlNode CloneNode (bool deep);
override this.CloneNode : bool -> System.Xml.XmlNode
Public Overrides Function CloneNode (deep As Boolean) As XmlNode

参数

deep
Boolean

若要递归地克隆指定节点下的子树,则为 true;若仅克隆节点本身,则为 false

返回

克隆的 XmlDocument 节点。

示例

以下示例显示了深层克隆和浅表克隆之间的差异。

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( "<book genre='novel' ISBN='1-861001-57-5'><title>Pride And Prejudice</title></book>" );
   
   //Create a deep clone.  The cloned node 
   //includes the child node.
   XmlDocument^ deep = dynamic_cast<XmlDocument^>(doc->CloneNode( true ));
   Console::WriteLine( deep->ChildNodes->Count );
   
   //Create a shallow clone.  The cloned node does not 
   //include the child node.
   XmlDocument^ shallow = dynamic_cast<XmlDocument^>(doc->CloneNode( false ));
   Console::WriteLine( "{0}{1}", shallow->Name, shallow->OuterXml );
   Console::WriteLine( shallow->ChildNodes->Count );
}

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

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Create a deep clone.  The cloned node
    //includes the child node.
    XmlDocument deep = (XmlDocument) doc.CloneNode(true);
    Console.WriteLine(deep.ChildNodes.Count);

    //Create a shallow clone.  The cloned node does not
    //include the child node.
    XmlDocument shallow = (XmlDocument) doc.CloneNode(false);
    Console.WriteLine(shallow.Name + shallow.OuterXml);
    Console.WriteLine(shallow.ChildNodes.Count);
  }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>"  & _
                    "<title>Pride And Prejudice</title>"  & _
                    "</book>")
        
        'Create a deep clone.  The cloned node 
        'includes the child node.
        Dim deep As XmlDocument = CType(doc.CloneNode(True), XmlDocument)
        Console.WriteLine(deep.ChildNodes.Count)
        
        'Create a shallow clone.  The cloned node does not 
        'include the child node.
        Dim shallow As XmlDocument = CType(doc.CloneNode(False), XmlDocument)
        Console.WriteLine(shallow.Name + shallow.OuterXml)
        Console.WriteLine(shallow.ChildNodes.Count)
    End Sub
End Class

注解

此方法用作节点的复制构造函数。 克隆的节点没有父 (ParentNode 返回 null) 。

如果 deeptrue,则克隆的节点包括所有子节点,否则仅克隆该 XmlDocument 节点。 XmlNode.CloneNode请参阅 方法,了解此方法在其他节点类型上的行为方式。

适用于