如何使用 XmlWriter 将编码属性添加到 utf-16 以外的 xml? [英] How to put an encoding attribute to xml other that utf-16 with XmlWriter?

查看:23
本文介绍了如何使用 XmlWriter 将编码属性添加到 utf-16 以外的 xml?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建一些 XmlDocument 的函数:

I've got a function creating some XmlDocument:

public string CreateOutputXmlString(ICollection<Field> fields)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.Encoding = Encoding.GetEncoding("windows-1250");

    StringBuilder builder = new StringBuilder();
    XmlWriter writer = XmlWriter.Create(builder, settings);

    writer.WriteStartDocument();
    writer.WriteStartElement("data");
    foreach (Field field in fields)
    {
        writer.WriteStartElement("item");
        writer.WriteAttributeString("name", field.Id);
        writer.WriteAttributeString("value", field.Value);
        writer.WriteEndElement();
    }
    writer.WriteEndElement();
    writer.Flush();
    writer.Close();

    return builder.ToString();
}

我设置了编码,但在我创建 XmlWriter 后,它确实有 utf-16 编码.我知道这是因为字符串(和我想的 StringBuilder)是用 utf-16 编码的,你不能改变它.
那么如何轻松地创建这个 xml 并将编码属性设置为windows-1250"呢?它甚至不必以这种编码进行编码,只需具有指定的属性即可.

I set an encoding but after i create XmlWriter it does have utf-16 encoding. I know it's because strings (and StringBuilder i suppose) are encoded in utf-16 and you can't change it.
So how can I easily create this xml with the encoding attribute set to "windows-1250"? it doesn't even have to be encoded in this encoding, it just has to have the specified attribute.

它必须在 .Net 2.0 中,因此不能使用任何新的框架元素.

edit: it has to be in .Net 2.0 so any new framework elements cannot be used.

推荐答案

您需要使用具有适当编码的 StringWriter.不幸的是 StringWriter 不允许你直接指定编码,所以你需要一个这样的类:

You need to use a StringWriter with the appropriate encoding. Unfortunately StringWriter doesn't let you specify the encoding directly, so you need a class like this:

public sealed class StringWriterWithEncoding : StringWriter
{
    private readonly Encoding encoding;

    public StringWriterWithEncoding (Encoding encoding)
    {
        this.encoding = encoding;
    }

    public override Encoding Encoding
    {
        get { return encoding; }
    }
}

(这个问题很相似,但并不完全重复.)

(This question is similar but not quite a duplicate.)

要回答评论:将 StringWriterWithEncoding 传递给 XmlWriter.Create 而不是 StringBuilder,然后在最后调用 ToString() .

To answer the comment: pass the StringWriterWithEncoding to XmlWriter.Create instead of the StringBuilder, then call ToString() on it at the end.

这篇关于如何使用 XmlWriter 将编码属性添加到 utf-16 以外的 xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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