C# 如何打印<;?xml版本=";1.0“&燃气轮机;使用XDocument

C# 如何打印<;?xml版本=";1.0“&燃气轮机;使用XDocument,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,使用ToString方法时,有没有办法让XDocument打印xml版本?让它输出如下内容: <?xml version="1.0"?> <!DOCTYPE ELMResponse [ ]> <Response> <Error> ... public static string ToStringWithDecl(this XDocument d) => $"{d.Declaration}{Environment.NewLine}{d}";

使用ToString方法时,有没有办法让XDocument打印xml版本?让它输出如下内容:

<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...
public static string ToStringWithDecl(this XDocument d)
  => $"{d.Declaration}{Environment.NewLine}{d}";
它将打印这个,这很好,但是它缺少“只需键入这个

var doc =
    new XDocument (
        new XDeclaration ("1.0", "utf-16", "no"),
        new XElement ("blah", "blih")
    );
你得到了什么

<?xml version="1.0" encoding="utf-16" standalone="no"?>
<blah>blih</blah>

哎呀

使用XDeclaration。这将添加声明

但是使用
ToString()
将无法获得所需的输出

您需要将
XDocument.Save()
与他的方法一起使用

全样本:

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

这是迄今为止最好的方法,也是最易于管理的:

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());
    }
}
我之所以这么说,是因为您可以通过将.UTF8更改为.Unicode或.UTF32来将编码更改为任何内容

代码

   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")
Dim\u根作为元素=
Dim _element1as XElement=我是元素一
Dim _element2as XElement=我是元素一
_root.Add(_element1)
_root.Add(_element2)
作为新XDocument的Dim文档(新XDeclaration(“1.0”、“UTF-8”、“是”),\u root)
_document.Save(“c:\xmlfolder\root.xml”)
输出注意(请在记事本中打开输出)


我是第一要素
我是第一要素

对一个老问题的回答太晚了,但我将尝试提供比其他答案更多的细节

您所问的问题称为XML声明

首先,
XDocument
具有此类型的属性。您可以使用
XDocument
构造函数的另一个重载:

var xdoc = new XDocument(
  new XDeclaration("1.0", null, null), // <--- here
  new XDocumentType("Response", null, null, "\n"), ... 
  );
但是,根据您以后保存或编写文档的方式,声明(或声明的一部分)可能会被忽略。稍后将详细介绍

XML声明可以有多种外观。以下是一些有效的示例:

<?xml version="1.0"?>                                        new XDeclaration("1.0", null, null)
<?xml version="1.1"?>                                        new XDeclaration("1.1", null, null)
<?xml version="1.0" encoding="us-ascii"?>                    new XDeclaration("1.0", "us-ascii", null)
<?xml version="1.0" encoding="utf-8"?>                       new XDeclaration("1.0", "utf-8", null)
<?xml version="1.0" encoding="utf-16"?>                      new XDeclaration("1.0", "utf-16", null)
<?xml version="1.0" encoding="utf-8" standalone="no"?>       new XDeclaration("1.0", "utf-8", "no")
<?xml version="1.0" encoding="utf-8" standalone="yes"?>      new XDeclaration("1.0", "utf-8", "yes")
<?xml version="1.0" standalone="yes"?>                       new XDeclaration("1.0", null, "yes")
其他一些答案表明,如果使用
xdoc.Save
xdoc.WriteTo
方法,则将遵守
XDeclaration
,但这并不完全正确:

  • 即使
    XDocument中没有XML声明,它们也可能包含XML声明
  • 它们可能指定目标文件、流、编写器、字符串生成器等使用的编码,而不是指定您给定的编码,或者如果您在
    xDecration
  • 他们可能会将您的版本从例如
    1.1
    更改为
    1.0
当然,在保存/写入文件时,声明与该文件的真实编码匹配是一件好事

但有时当您在mememory中写入字符串时,您不需要
utf-16
(即使您意识到.NET字符串在内部是utf-16)。您可以使用上面的扩展方法。或者您可以使用EricSch答案中的以下黑客版本的方法:

  string xdocString;
  using (var hackedWriter = new SuppressEncodingStringWriter())
  {
    xdoc.Save(hackedWriter);
    xdocString = hackedWriter.ToString();
  }
如果您有:

// a string writer which claims its encoding is null in order to omit encoding in XML declarations
class SuppressEncodingStringWriter : StringWriter
{
  public sealed override Encoding Encoding => null;
}
更简单的方法是:

var fullXml = $"{xDocument.Declaration}{xDocument}";

如果您的xDocument.Declaration为空,只需添加即可。

是的,他说他在使用ToString()时我错过了部分。因此,请使用XDeclaration和Save()(用于文件或内存流)。或通过stringwriter创建字符串;-)只需wr.ToString()即可工作,无需使用GetStringBuilder()在betweenTip中:您可以创建一个扩展方法,将功能添加到
ToString
方法中。例如
公共静态字符串ToString(此XDocument文档,bool addDeclaration)
此答案仅适用于utf-16,因为它使用StringWriter将流编码为utf-16。其ToString()方法一致地修改声明。对于utf-8,您可以使用@Kevin的答案。此外,由于问题表明使用DTD,standalone必须为“否”。旁注:XDocument.ToString()省略XDeclaration还意味着您将不会在VS debugger监视窗口中看到声明,即使XDeclaration在XDocument中。
public static string ToStringWithDecl(this XDocument d)
  => $"{d.Declaration}{Environment.NewLine}{d}";
  string xdocString;
  using (var hackedWriter = new SuppressEncodingStringWriter())
  {
    xdoc.Save(hackedWriter);
    xdocString = hackedWriter.ToString();
  }
// a string writer which claims its encoding is null in order to omit encoding in XML declarations
class SuppressEncodingStringWriter : StringWriter
{
  public sealed override Encoding Encoding => null;
}
var fullXml = $"{xDocument.Declaration}{xDocument}";