Add XDeclaration to XDocument after creating it

I have an XmlSerializer that I use to serialize an object in an XDocument.

var doc = new XDocument(); using (var writer = doc.CreateWriter()) { xmlSerializer.Serialize(writer, object); } 

After that, I want to add XDeclaration:

 <?xml version="1.0" encoding="UTF-8" standalone="no"?> 

I will build this XDeclaration as described below:

 var decl = new XDeclaration("1.0", "UTF-8", "no"); 

However, when I try to add this XDeclartion to my XDocument, I get the following error:

 System.ArgumentException : Non white space characters cannot be added to content. 

I have been searching Google for some time, but all I found is adding XDeclaration to the XDocument constructor, which in my case (when filling it with XmlWriter) is not acceptable.

+4
source share
1 answer

Use property XDocument.Declaration


EDIT

Code example:

 var xmlSerializer = new XmlSerializer(typeof(int)); var doc = new XDocument(); var decl = new XDeclaration("1.0", "utf-8", "no"); doc.Declaration = decl; using (var writer = doc.CreateWriter()) { xmlSerializer.Serialize(writer, 1); } doc.Save(File.Create("x.xml")); 

This code produced the following result:

 <?xml version="1.0" encoding="utf-8" standalone="no"?> <int>1</int> 
+6
source

All Articles