JMK
JMK

Reputation: 28059

Adding document type to XML using XDeclaration

I am trying to add an XDeclaration to an XML document like so:

XDocument doc = new XDocument();
XDeclaration dc = new XDeclaration("1.0", "utf-8", "no");
XNamespace ns = "http://www.foo.com/bar";

doc.Add(dc);

However, I get the following error:

Non white space characters cannot be added to content.

If I take away the XDeclaration line the code works fine, where am I going wrong?

Upvotes: 0

Views: 1002

Answers (2)

Steves
Steves

Reputation: 3224

XDeclaration is not a valid content of XDocument. Use instead property Declaration.

Upvotes: 1

curtisk
curtisk

Reputation: 20175

You want to set the declaration like this, not with .Add like you tried:

doc.Declaration = dc;

Or it can be set when instantiating the xDocument with this constructor

Upvotes: 5

Related Questions