XmlAttribute.CloneNode(Boolean) Méthode

Définition

Crée un doublon de ce nœud.

C#
public override System.Xml.XmlNode CloneNode (bool deep);

Paramètres

deep
Boolean

true pour cloner récursivement la sous-arborescence sous le nœud spécifié ; false pour cloner seulement le nœud lui-même.

Retours

XmlNode

Doublon du nœud.

Exemples

L’exemple suivant utilise CloneNode pour ajouter un attribut à deux nœuds d’élément différents.

C#
using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create an XmlDocument.
    XmlDocument doc = new 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 = (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 = (XmlAttribute) attr.CloneNode(true);
    currNode = (XmlElement) doc.DocumentElement.LastChild;
    currNode.SetAttributeNode(attr2);

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

L’exemple utilise le fichier, 2elems.xmlcomme entrée.

XML

<!--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>

Remarques

Cette méthode sert de constructeur de copie pour les nœuds. Le nœud cloné n’a pas de parent (ParentNode retourne null).

Le clonage d’un attribut non spécifié retourne un attribut spécifié (Specified retourne true).

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

Voir aussi