XDocument.ToString()删除XML编码标签 [英] XDocument.ToString() drops XML Encoding Tag

查看:192
本文介绍了XDocument.ToString()删除XML编码标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在toString()函数中获取xml编码吗?

Is there any way to get the xml encoding in the toString() Function?

示例:

xml.Save("myfile.xml");

导致

<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>

但是

tb_output.Text = xml.toString();

导致这样的输出

<Cooperations>
  <Cooperation>
    <CooperationId>xxx</CooperationId>
    <CooperationName>Allianz Konzern</CooperationName>
    <LogicalCustomers>
    ...

推荐答案

要么显式写出声明,要么使用StringWriter并调用Save():

Either explicitly write out the declaration, or use a StringWriter and call 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);
    }
}

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

You could easily add that as an extension method:

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

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

This has the advantage that it won't go bang if there isn't a declaration :)

然后您可以使用:

string x = doc.ToStringWithDeclaration();

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

Note that that will use utf-16 as the encoding, because that's the implicit encoding in StringWriter. You can influence that yourself though by creating a subclass of StringWriter, e.g. to always use UTF-8.

这篇关于XDocument.ToString()删除XML编码标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆