强制XDocument使用UTF-8编码写入String

时间:2010-10-06 10:56:34

标签: c# xml utf-8 linq-to-xml

我希望能够使用声明和UTF-8编码将XML写入String。这似乎很难完成。

我已经阅读了一些并尝试了一些流行的答案,但他们都有问题。我当前的代码正确输出为UTF-8但不保持XDocument的原始格式(即缩进/空格)!

有人可以提供一些建议吗?

XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xelementXML);

MemoryStream ms = new MemoryStream();
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
    xml.Save(xw);
    xw.Flush();

    StreamReader sr = new StreamReader(ms);
    ms.Seek(0, SeekOrigin.Begin);

    String xmlString = sr.ReadToEnd();
}

XML要求格式化与.ToString()格式化格式相同,即

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
    <node>blah</node>
</root>

我目前看到的是

<?xml version="1.0" encoding="utf-8" standalone="yes"?><root><node>blah</node></root>

更新 我已经设法通过添加XmlTextWriter设置来实现这一点......但它看起来非常笨重!

MemoryStream ms = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;
using (XmlWriter xw = XmlTextWriter.Create(ms, settings))
{
    xml.Save(xw);
    xw.Flush();

    StreamReader sr = new StreamReader(ms);
    ms.Seek(0, SeekOrigin.Begin);
    String blah = sr.ReadToEnd();
}

3 个答案:

答案 0 :(得分:59)

试试这个:

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

class Test
{
    static void Main()
    {
        XDocument doc = XDocument.Load("test.xml",
                                       LoadOptions.PreserveWhitespace);
        doc.Declaration = new XDeclaration("1.0", "utf-8", null);
        StringWriter writer = new Utf8StringWriter();
        doc.Save(writer, SaveOptions.None);
        Console.WriteLine(writer);
    }

    private class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }
}

当然,您还没有向我们展示您是如何构建文档的,这使得测试变得困难......我只是尝试使用手工构造的XDocument并且包含相关的空格太

答案 1 :(得分:1)

尝试XmlWriterSettings:

XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = false;
xws.Indent = true;

并将其传递给

using (XmlWriter xw = XmlWriter.Create(sb, xws))

答案 2 :(得分:0)

另请参阅https://stackoverflow.com/a/3288376/1430535

.then(response => this.setState({courses: response}))