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

后端 未结 6 1087
暗喜
暗喜 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 03:00

    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());
    

提交回复
热议问题