Unexpected exception from XDocument constructor

Wim Coenen picture Wim Coenen · Sep 17, 2009 · Viewed 9.7k times · Source

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?

Answer

Drew Noakes picture Drew Noakes · Sep 19, 2011

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);