如何使用xmlWriter将编码属性放入xml其他utf-16? [英] How to put an encoding attribute to xml other that utf-16 with 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,你不能改变它。
那么如何轻松地创建这个xml的encoding属性设置为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将编码属性放入xml其他utf-16?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!