0

将现有 XML 保存到新位置时,实体从内容中转义并替换为问号

请参阅实体下方的快照 - ( - 作为十六进制)在读取时存在,但在保存到另一个位置后替换为问号。

作为内部 XML 读取时

作为内部 XML 读取时

作为内部文本阅读时

作为内部文本阅读时

保存 XML 文件后

保存 XML 后

编辑 1 下面是我的代码

string path = @"C:\work\myxml.XML";
string pathnew = @"C:\work\myxml_new.XML";
//GetFileEncoding(path);
XmlDocument document = new XmlDocument();
XmlDeclaration xmlDeclaration = document.CreateXmlDeclaration("1.0","US-ASCII",null);
//document.CreateXmlDeclaration("1.0", null, null);
document.Load(path);
string x = document.InnerText;
document.Save(pathnew);

编辑 2 我的源文件如下所示。我需要保留实体

在此处输入图像描述

4

1 回答 1

3

这里的问题似乎XmlWriterXmlDocument.

如果您自己创建,问题就会消失XmlWriter- 不受支持的字符将被正确编码为实体引用。这XmlWriter是一个不同的(和更新的)实现,EncoderFallback它将字符编码为无法编码的字符的实体引用。根据文档中的注释,默认的回退机制是对问号进行编码。

var settings = new XmlWriterSettings
{
    Indent = true,
    Encoding = Encoding.GetEncoding("US-ASCII")
};

using (var writer = XmlWriter.Create(pathnew, settings))
{
    document.Save(writer);            
}

顺便说一句,我建议使用 LINQ to XML XDocumentAPI,它比老旧的XmlDocumentAPI 更好用。而且它的版本Save也不存在这个问题!

于 2016-05-10T15:25:19.313 回答