How to print <? Xml version = "1.0"?> Using XDocument
Is there a way for XDocument to print the xml version using the ToString method? 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 good, but there is no version of "lt ;? xml" as mentioned above.
<!DOCTYPE ELMResponse [ ]> <Response> <Error> ... I know that you can do this by manually outputting it. Just wanted to know if this is possible with XDocument.
Using XDeclaration. This will add a declaration.
But with ToString you will not get the desired result.
You need to use XDocument.Save () with one of its 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()); This is by far the best and most manageable way:
var xdoc = new XDocument(new XElement("Root", new XElement("Child", "ε°ε TaΜibeΜi."))); string mystring; using(var sw = new MemoryStream()) { using(var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8)) { xdoc.Save(strw); mystring = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray()); } } and I say this only because you can change the encoding to anything by changing .UTF8 to .Unicode or .UTF32
Just enter 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> VB.NET Solution CODE
the code
Dim _root As XElement = <root></root> Dim _element1 As XElement = <element1>i am element one</element1> Dim _element2 As XElement = <element2>i am element one</element2> _root.Add(_element1) _root.Add(_element2) Dim _document As New XDocument(New XDeclaration("1.0", "UTF-8", "yes"), _root) _document.Save("c:\xmlfolder\root.xml") Output Note (please open the output in notepad)
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <root> <element1>i am element one</element1> <element2>i am element one</element2> </root>