Peter
Peter

Reputation: 114

Add XDeclaration to XDocument after it's constructed

I have an XmlSerializer which I use to Serialize an object to an XDocument.

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

After this is done, I want to add a XDeclaration:

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

I construct 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 searched Google for some time but all I've found is adding the XDeclaration to the constructor of the XDocument which in my case (when filling it with a XmlWriter) is not acceptable.

Upvotes: 4

Views: 6901

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

Use property XDocument.Declaration


EDIT:

Sample code:

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 following output:

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

Upvotes: 6

Related Questions