Partager via


Sérialisation avec une déclaration XML

Cette rubrique décrit comment contrôler si la sérialisation génère une déclaration XML.

Génération de déclaration XML

La sérialisation vers un objet File ou TextWriter à l'aide de la méthode XElement.Save ou XDocument.Savegénère une déclaration XML.Lorsque vous sérialisez vers un objet XmlWriter, les paramètres de writer (spécifiés dans un objet XmlWriterSettings) déterminent si une déclaration XML est générée ou non.

Si vous sérialisez vers une chaîne à l'aide de la méthode ToString, le code XML résultant n'inclura pas de déclaration XML.

Sérialisation avec une déclaration XML

L'exemple suivant crée un objet XElement, enregistre le document dans un fichier, puis imprime le fichier sur la console :

XElement root = new XElement("Root",
    new XElement("Child", "child content")
);
root.Save("Root.xml");
string str = File.ReadAllText("Root.xml");
Console.WriteLine(str);
Dim root As XElement = <Root>
                           <Child>child content</Child>
                       </Root>
root.Save("Root.xml")
Dim str As String = File.ReadAllText("Root.xml")
Console.WriteLine(str)

Cet exemple produit la sortie suivante :

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child>child content</Child>
</Root>

Sérialisation sans déclaration XML

L'exemple suivant montre comment enregistrer un objet XElement dans un objet XmlWriter.

StringBuilder sb = new StringBuilder();
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;

using (XmlWriter xw = XmlWriter.Create(sb, xws)) {
    XElement root = new XElement("Root",
        new XElement("Child", "child content")
    );
    root.Save(xw);
}
Console.WriteLine(sb.ToString());
Dim sb As StringBuilder = New StringBuilder()
Dim xws As XmlWriterSettings = New XmlWriterSettings()
xws.OmitXmlDeclaration = True

Using xw As XmlWriter = XmlWriter.Create(sb, xws)
    Dim root = <Root>
                   <Child>child content</Child>
               </Root>
    root.Save(xw)
End Using
Console.WriteLine(sb.ToString())

Cet exemple génère la sortie suivante :

<Root><Child>child content</Child></Root>

Voir aussi

Concepts

Sérialisation d'arborescences XML