LINQ to XML: Non white space characters cannot be added to content.

I got this error when setting up some LINQ to XML code and I couldn't figure out why I kept getting this error as it made no sense.  After doing a quick search, I realized my root element was this:

var o = new XElement("statement", query.Statement);

and I realized that it was housing content and couldn't be stored in this way.... the root element was a text node like:

<statement>some statement</statement>

And so, switching it to:

XElement queryElement = new XElement("query", new XElement("statement", query.Statement));

 

And so switching it to this, with a root element like:

<query>
    <statement>my statement</statement>
</query>

Helped.  The other thing that solved the issue was how I was creating the document.  I was trying to create the entire XML tree and then assign it to the document via its content property in the constructor.  This didn't work, and the solution was to first create the document, then create the root node and add it, along with the rest of the document.

XDocument document = new XDocument();

XElement queryElement = new XElement("query");

document.Add(queryElement);


Maybe that is a bug, I'm not sure, but I can't assign query directly via the constructor.  I get an error.

You can create the XML in one shot, via the way LINQ to XML works, but I can't in this scenario based on how I have to write the content out, which is why you don't see that in my example.

Published Saturday, July 25, 2009 5:22 PM by bmains
Filed under: ,

Comments

No Comments