views:

1390

answers:

2

Is there any way to have an XDocument print the xml version when using the ToString method? Have it output something like this:

<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

I have the following:

var xdoc = new XDocument(new XDocumentType("Response", null, null, "\n"), ...

which will print this which is fine, but it is missing the "<?xml version" as stated above.

<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

I know that you can do this by outputting it manually my self. Just wanted to know if it was possible by using XDocument.

+4  A: 

Just type this

var doc =
    new XDocument (
     new XDeclaration ("1.0", "utf-16", "no"),
     new XElement ("blah", "blih")
    );

And you get

<?xml version="1.0" encoding="utf-16" standalone="no"?>
<blah>blih</blah>
Yann Schwartz
Not fully correct, ToString will not work.
EricSch
We should stop meeting like this :-)
Yann Schwartz
The rouble is I use LinqPad to test and I missed the Save...
Yann Schwartz
In addition, as the question indicates the use of a DTD, standalone must be "no".
Greg Beech
Greg: edited to reflect your mindful comment.
Yann Schwartz
+12  A: 

By using XDeclaration. This will add the declaration.

But with ToString you will not get the desired output.

You need to use XDocument.Save() with one of his methods.

Full sample:

    var doc = new XDocument(
            new XDeclaration("1.0", "utf-16", "yes"), 
            new XElement("blah", "blih"));

    var wr = new StringWriter();
    doc.Save(wr);
    Console.Write(wr.GetStringBuilder().ToString());
EricSch
Yep you're right, I missed the part when he said he was using ToString(). So, use XDeclaration AND Save() (to file or a memorystream).
Yann Schwartz
or to a string via stringwriter ;-)
EricSch
Similar comment to above, as the question indicated a DTD, standalone must be "no".
Greg Beech