【问题标题】:Why XDocument encoding type changed while use XDocument's WriteTo method为什么在使用 XDocument 的 WriteTo 方法时 XDocument 编码类型发生了变化
【发布时间】:2017-09-14 13:07:47
【问题描述】:

我已经使用 XDocument 创建了简单的 xml 文档。我已经使用 XDocument 和 XDeclaration 创建了文档。

XDocument encodedDoc8 = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Root", "Content"));

如果我将此文档保存到文件中,则表示编码类型未更改。

using (TextWriter sw = new StreamWriter(@"C:\sample.txt", false)){
   encodedDoc8.Save(sw);
}

输出:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>Content</Root>   

但是,如果我使用 XDocument 的 WriteTo 方法打印 xml 意味着编码类型发生了变化。

using (XmlWriter writ = XmlWriter.Create(Console.Out))
{
   encodedDoc8.WriteTo(writ);
}

输出:

<?xml version="1.0" encoding="IBM437" standalone="yes"?><Root>Content</Root>

为什么会这样?请更新您的答案。提前致谢。

【问题讨论】:

标签: c# xml linq


【解决方案1】:

如果你查看reference sourceXmlWriter.Create,调用链最终会导致这个构造函数:

public XmlTextWriter(TextWriter w) : this() {
    textWriter = w;
    encoding = w.Encoding;
    xmlEncoder = new XmlTextEncoder(w);
    xmlEncoder.QuoteChar = this.quoteChar;
}

分配encoding = w.Encoding 解释了您的情况:Console.Out 文本编写器的Encoding 设置被复制到新创建的XmlTextWriterencoding 设置,替换编码您在XDocument 中提供的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2011-07-17
    • 2022-12-02
    相关资源
    最近更新 更多