XDocument.ToString()删除XML编码标记

Hen*_*sel 100 c# linq-to-xml

有没有办法在toString()函数中获取xml编码?

例:

xml.Save("myfile.xml");
Run Code Online (Sandbox Code Playgroud)

导致

<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>
Run Code Online (Sandbox Code Playgroud)

tb_output.Text = xml.toString();
Run Code Online (Sandbox Code Playgroud)

导致像这样的输出

<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>
    ...
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 97

要么明确写出声明,要么使用StringWriter和调用Save():

using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = @"<?xml version='1.0' encoding='utf-8'?>
<Cooperations>
  <Cooperation />
</Cooperations>";

        XDocument doc = XDocument.Parse(xml);
        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new StringWriter(builder))
        {
            doc.Save(writer);
        }
        Console.WriteLine(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以轻松地将其添加为扩展方法:

public static string ToStringWithDeclaration(this XDocument doc)
{
    if (doc == null)
    {
        throw new ArgumentNullException("doc");
    }
    StringBuilder builder = new StringBuilder();
    using (TextWriter writer = new StringWriter(builder))
    {
        doc.Save(writer);
    }
    return builder.ToString();
}
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,如果没有声明,它就不会爆炸:)

然后你可以使用:

string x = doc.ToStringWithDeclaration();
Run Code Online (Sandbox Code Playgroud)

请注意,这将使用utf-16作为编码,因为这是隐式编码StringWriter.您可以通过创建子类来自己影响StringWriter,例如始终使用UTF-8.

  • 这有一个小问题,XDocument声明中的编码被忽略,并在执行保存时被StringWriter的编码所取代,这可能是你想要的,也可能不是你想要的 (14认同)
  • 发现使用上面的扩展方法更容易,但返回以下内容... return doc.Declaration + doc.ToString(); 如果声明为null,则只会产生一个空字符串. (12认同)
  • 然后将扩展方法与来自http://stackoverflow.com/a/1564727/75963的Utf8StringWriter结合使用;) (2认同)

Rya*_*ner 45

Declaration属性将包含XML声明.要获取内容和声明,您可以执行以下操作:

tb_output.Text = xml.Declaration.ToString() + xml.ToString()
Run Code Online (Sandbox Code Playgroud)

  • 看来你的xdocument中没有使用新的XDeclaration("1.0","utf-8","yes"),这会产生错误,因为xml.Declaration为null.但xml.save似乎自动检测正确的编码. (7认同)
  • 或`... = $“ {xdoc.Declaration} {Environment.NewLine} {xdoc}”;` (2认同)

小智 9

用这个:

output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
Run Code Online (Sandbox Code Playgroud)

  • 如果不创建新的XDeclaration(“ 1.0”,“ utf-8”,“ yes”)并将其添加到XDocument或其他对象中,则xml.Declaration.ToString()将引发null异常。 (2认同)