使用 XDocument" />

如何打印使用 XDocument

发布于 2024-08-31 08:09:27 字数 497 浏览 4 评论 0 原文

使用 ToString 方法时,有什么方法可以让 XDocument 打印 xml 版本吗?让它输出类似这样的内容:

<?xml version="1.0"?>
<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

我有以下内容:

var xdoc = new XDocument(new XDocumentType("Response", null, null, "\n"), ...

它将打印这个,这很好,但它缺少如上所述的“

<!DOCTYPE ELMResponse [
]>
<Response>
<Error> ...

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

Is there any way to have an XDocument print the xml version when using the ToString method? Have it 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 fine, but it is missing the "<?xml version" as stated above.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅唱ヾ落雨殇 2024-09-07 08:09:27

通过使用 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());

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());
來不及說愛妳 2024-09-07 08:09:27

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

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 来将编码更改为任何内容

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

叹梦 2024-09-07 08:09:27

对一个老问题的迟到回答,但我将尽力提供比其他答案更多的细节。

您所询问的内容称为 XML 声明

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

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

或者稍后设置该属性:

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

但这取决于您保存或写入的方式XDocument 之后,声明(或其部分)可能会被忽略。稍后会详细介绍。

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

请注意,XDeclaration 很乐意接受无效参数,因此您需要确保其正确。

在许多情况下,第一个 (您要求的形式)是完美的(不需要提供 encoding如果它只是 UTF-8(包括 ASCII),并且如果其预期值为 "no" 或没有 DTD,则不需要指定 standalone)。

请注意,xdoc.ToString() 会从 XNode 基类(在我的 .NET 版本中)进行覆盖,并且不包含 XML 声明。您可以轻松地创建一个方法来处理这个问题,如下所示:

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

其他一些答案表明,如果您使用 xdoc.Save,则将遵守 XDeclaration >xdoc.WriteTo 方法,但这并不完全正确:

  • 即使您的 XDocument 中没有 XML 声明,它们也可能包含 XML 声明。
  • 它们可能指定目标文件、流使用的编码、编写器、字符串生成器等,而不是您提供的编码,或者如果您在 XDeclaration 中这样做,则不是省略编码,
  • 他们可能会将您的版本从例如 1.1 更改为1.0

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

但有时,当您写入内存中的字符串时,您不需要 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;
}

加法。无论是谁更新了类型 StringWriter(及其基类型 TextWriter)以使用nuallable 引用类型,都决定使用诸如 编码FormatProvider 不应该可以为空。也许这很不幸?无论如何,如果您打开了可为 null 的引用类型,则可能需要编写 null! 而不仅仅是 null

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.

First of all, the XDocument has a property Declaration of type XDeclaration for this. You can either user another overload of the XDocument constructor:

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 save or write your XDocument later, the declaration (or parts of it) may be ignored. More on that later.

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

<?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 XDeclaration will happily accept invalid arguments, so it is up to you to get it right.

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

Note that xdoc.ToString() goes do the override from the XNode base 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:

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

Some of the other answers indicate that the XDeclaration will be respected if you use xdoc.Save or xdoc.WriteTo methods, but that is not quite true:

  • 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.1 into 1.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:

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

Addition. Whoever updated the type StringWriter (and its base type TextWriter) to use nuallable reference types, decided that properties such as Encoding and FormatProvider should not be nullable. Maybe that was unfortunate? Anyway, if you have nullable reference types turned on, you may need to write null! instead of just null.

迷爱 2024-09-07 08:09:27

只要输入这个

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>

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>
木緿 2024-09-07 08:09:27

VB.NET解决方案代码

代码

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

输出 注意(请在记事本中打开输出)

 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
 <root>
   <element1>i am element one</element1>
   <element2>i am element one</element2>
</root>

VB.NET Solution CODE

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 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>
蓝咒 2024-09-07 08:09:27

更简单的方法是:

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

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

The easier way is:

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

If your xDocument.Declaration is empty, just add it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文