Wim Coenen
Wim Coenen

Reputation: 66783

Unexpected exception from XDocument constructor

This works fine:

XDocument xdoc = new XDocument(
   new XDeclaration("1.1", "UTF-8", "yes"),
   new XProcessingInstruction("foo", "bar"),
   new XElement("test"));

However if I change it to pass the "params array" explicitly as an array:

object[] content = new object[] {
   new XDeclaration("1.1", "UTF-8", "yes"),
   new XProcessingInstruction("foo", "bar"),
   new XElement("test")
};
xdoc = new XDocument(content);

It fails with:

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

Aren't these two examples exactly equivalent? What's going on here?

Upvotes: 17

Views: 9794

Answers (2)

Drew Noakes
Drew Noakes

Reputation: 311285

You can get this error when parsing XML strings if you use the XDocument constructor instead of a factory method.

Given:

var xmlString = "<some-xml />";

This fails:

var doc = new XDocument(xmlString);

This works:

var doc = XDocument.Parse(xmlString);

Upvotes: 20

BFree
BFree

Reputation: 103760

When you use the first method, you're using the overload of XDocument that first takes an XDeclaration and then a params for the content. However, when you're using the second approach, you're using the overload which takes a params for content. The XDeclaration in your object[] array is coming through as content, and that's where it's blowing up.

See here : http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.xdocument.aspx

Upvotes: 14

Related Questions