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

后端 未结 6 1086
暗喜
暗喜 2020-11-29 02:16

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

         


        
6条回答
  •  天涯浪人
    2020-11-29 02:48

    This is by far the best way and most managable:

    var xdoc = new XDocument(new XElement("Root", new XElement("Child", "台北 Táibě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 that just because you can change encoding to anything by changing .UTF8 to .Unicode or .UTF32

提交回复
热议问题