编码案例未保留 [英] Encoding case not preserved
问题描述
我正在使用XmlDocument和StreamWriter保存xml文件。
I'm saving a xml file using XmlDocument and StreamWriter.
当我检查xmlDocument.innerXml时,它会向我显示encoding =" UTF-8"但是在保存到文件编码后会转换为小写"utf-8" ;。有没有办法保持编码的情况。通过指定
大写"UTF-8"来创建前导码。
When I inspect the xmlDocument.innerXml, it shows me the encoding="UTF-8", however after saving to a file encoding is getting converted to lower case "utf-8". Is there any way to preserve the case of encoding as it is. Preamble is created by specifying the upper case "UTF-8".
如果StreamWriter无法实现,那么保存/编写没有BOM的XmlDocument的其他方法?
If its not possible with StreamWriter are there any other ways to save/write an XmlDocument without BOM?
提前致谢
Sandy
推荐答案
我认为问题是编码类的名称以小写形式返回"utf-8",所以我试图从UTF8Encoding类继承并覆盖名称以使用大写字母:
I think the problem is that the name of the encoding class is returned in lower case "utf-8", so I tried to inherit from the UTF8Encoding class and override the name to use upper case letters:
public class MyUTF8Encoding : UTF8Encoding
{
public MyUTF8Encoding(bool encoderShouldEmitUTF8Identifier) : base(encoderShouldEmitUTF8Identifier) { }
public override string EncodingName
{
get
{
return base.EncodingName.ToUpper();
}
}
public override string WebName
{
get
{
return base.WebName.ToUpper();
}
}
}
然后我按如下方式使用它:
Then I use it as follows:
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
doc.AppendChild(doc.CreateElement("Root"));
doc.DocumentElement.InnerText = "ä߀";
XmlWriterSettings xws = new XmlWriterSettings()
{
Encoding = new MyUTF8Encoding(false),
Indent = true
};
using (XmlWriter xw = XmlWriter.Create("file.xml", xws))
{
doc.Save(xw);
}
据我所知,生成的文件在XML声明中有UTF-8。这是否值得我不确定但是请告诉我们这种方法是否适合您的需求。
As far as I can tell the resulting file then has UTF-8 in the XML declaration. Whether that is worth the trouble I am not sure however but let us know whether the approach suits your needs.
这篇关于编码案例未保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!