C# 如何使用 XDocument 打印 <?xml version="1.0"?>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/957124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:14:05  来源:igfitidea点击:

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

c#xmllinq-to-xml

提问by JD Frias

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

使用 ToString 方法时,有没有办法让 XDocument 打印 xml 版本?让它输出这样的东西:

<?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.

它将打印这个很好,但它缺少如上所述的“<?xml 版本”。

<!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.

我知道你可以通过我自己手动输出来做到这一点。只是想知道是否可以使用 XDocument。

采纳答案by EricSch

By using XDeclaration. This will add the declaration.

通过使用 XDeclaration。这将添加声明。

But with ToString()you will not get the desired output.

但是ToString()你不会得到想要的输出。

You need to use XDocument.Save()with one of his methods.

您需要使用XDocument.Save()他的方法之一。

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

回答by Yann Schwartz

Just type 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>

回答by Kevin

This is by far the best way and most managable:

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

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 that just because you can change encoding to anything by changing .UTF8 to .Unicode or .UTF32

我这么说只是因为您可以通过将 .UTF8 更改为 .Unicode 或 .UTF32 来更改任何编码

回答by Abdul Saboor

VB.NET Solution CODE

VB.NET 解决方案代码

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")

OutputNote(please open 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>

回答by Jeppe Stig Nielsen

Late answer to an old question, but I shall try to provide more details than the other answers.

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

The thing you ask about, is called an XML declaration.

您询问的内容称为XML 声明

First of all, the XDocumenthas a property Declarationof type XDeclarationfor this. You can either user another overload of the XDocumentconstructor:

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

var xdoc = new XDocument(
  new XDeclaration("1.0", null, null), // <--- here
  new XDocumentType("Response", null, null, "\n"), ... 
  );

or set the property later:

或稍后设置属性:

xdoc.Declaration = new XDeclaration("1.0", null, null);

But depending on how you saveor writeyour XDocumentlater, the declaration (or parts of it) may be ignored. More on that later.

但是根据您以后保存编写的方式XDocument,声明(或其中的一部分)可能会被忽略。稍后再谈。

The XML declaration can have a number of appearances. Here are some valid examples:

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")

Note that XDeclarationwill happily accept invalid arguments, so it is up to you to get it right.

请注意,它XDeclaration会很乐意接受无效参数,因此由您来正确处理。

In many cases the first one, <?xml version="1.0"?>, the form you ask for, is perfect (it is not needed to give encodingif it is just UTF-8 (including ASCII), and it is not needed to specify standaloneif its intended value is "no"or if there are no DTDs).

在许多情况下,第一个,<?xml version="1.0"?>您要求的形式是完美的(encoding如果它只是 UTF-8(包括 ASCII),则不需要给出,并且不需要指定standalone它的预期值"no"是否存在或是否存在没有 DTD)。

Note that xdoc.ToString()goes do the override from the XNodebase class (in my version of .NET) and does not include the XML declaration. You can easily enough create a method to deal with that, like this:

请注意,xdoc.ToString()XNode基类(在我的 .NET 版本中)进行覆盖并且不包括 XML 声明。你可以很容易地创建一个方法来处理它,像这样:

public static string ToStringWithDecl(this XDocument d)
  => $"{d.Declaration}{Environment.NewLine}{d}";

Some of the other answers indicate that the XDeclarationwill be respected if you use xdoc.Saveor xdoc.WriteTomethods, but that is not quite true:

其他一些答案表明,XDeclaration如果您使用xdoc.Savexdoc.WriteTo方法,将会受到尊重,但这并不完全正确:

  • They might include an XML declaration even if you have none in your XDocument
  • They might specify the encoding used by the target file, stream, writer, string builder etc. instead of the encoding you gave, or instead of omitting the encoding if you did that in your XDeclaration
  • They might change your version from e.g. 1.1into 1.0
  • 它们可能包含 XML 声明,即使您的文件中没有 XDocument
  • 他们可能会指定目标文件、流、编写器、字符串构建器等使用的编码,而不是您提供的编码,或者如果您在 XDeclaration
  • 他们可能会将您的版本从 eg 更改1.11.0

Of course, when you save/write to a file, it is a good thing that the declaration matches the true encoding of that file!

当然,当您保存/写入文件时,声明与该文件的真实编码匹配是一件好事!

But sometimes when you write to a string in mememory, you do not want the utf-16(even if you realize that .NET strings are in UTF-16 internally). You can use the extension method above instead. Or you can use the following hacked version of the method from EricSch's answer:

但有时当您写入内存中的字符串时,您不想要utf-16(即使您意识到 .NET 字符串在内部使用 UTF-16)。您可以改用上面的扩展方法。或者您可以使用 EricSch's answer 中该方法的以下黑客版本:

  string xdocString;
  using (var hackedWriter = new SuppressEncodingStringWriter())
  {
    xdoc.Save(hackedWriter);
    xdocString = hackedWriter.ToString();
  }

where you have:

你有:

// 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;
}

回答by Juan Carlos Girón

The easier way is:

更简单的方法是:

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

If your xDocument.Declarationis empty, just add it.

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