如何把一个编码属性XML以外的UTF-16的XmlWriter? [英] How to put an encoding attribute to xml other that utf-16 with XmlWriter?

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

问题描述

我有一个功能,创造了一些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 codeD,你不能改变它。结果
所以,我怎么能轻松地创建这个XML设置为Windows-1250编码属性?它甚至不必须是EN codeD此编码,它只是必须有指定的属性。

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

(<一个href=\"http://stackoverflow.com/questions/371930/-net-xmlwriter-unexpected-encoding-is-confusing-me\">This问题是类似的,但并不完全是重复的。)

(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.

这篇关于如何把一个编码属性XML以外的UTF-16的XmlWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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