Serializing with an XML Declaration
This topic describes how to control whether serialization generates an XML declaration.
XML Declaration Generation
Serializing to a File or a TextWriter using the XElement.Save method or the XDocument.Save method generates an XML declaration. When you serialize to an XmlWriter, the writer settings (specified in an XmlWriterSettings object) determine whether an XML declaration is generated or not.
If you are serializing to a string using the ToString method, the resulting XML will not include an XML declaration.
Serializing with an XML Declaration
The following example creates an XElement, saves the document to a file, and then prints the file to the 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)
This example produces the following output:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child>child content</Child>
</Root>
Serializing without an XML Declaration
The following example shows how to save an XElement to an 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())
This example produces the following output:
<Root><Child>child content</Child></Root>