Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print <?xml version="1.0"?> using XDocument

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.

like image 346
JD Frias Avatar asked Jun 05 '09 17:06

JD Frias


People also ask

What is the use of <? Xml version 1.0 ?>?

<? xml version="1.0"?> is an XML declaration. It is an optional indication of the version of XML, the character encoding, and the standalone document declaration. It can only appear as the very top of an XML file, if anywhere, and may not be repeated.

Is <? XML required?

Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version , followed by any encoding , followed by any standalone .


1 Answers

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.ToString()); 
like image 166
EricSch Avatar answered Sep 29 '22 13:09

EricSch