Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 204
Wim Coenen Avatar asked Sep 17 '09 13:09

Wim Coenen


2 Answers

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);
like image 165
Drew Noakes Avatar answered Nov 02 '22 09:11

Drew Noakes


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

like image 30
BFree Avatar answered Nov 02 '22 08:11

BFree