简体   繁体   English

使用XML DOCUMENT将XML文件从一个位置保存到另一位置

[英]Saving XML file from one location to another location using XML DOCUMENT

While saving the existing XML to new location, entities escaped from the content and replaced with Question Mark 在将现有XML保存到新位置的同时,实体从内容中转义并替换为问号

See the snaps below entity ‐ (- as Hex) present while reading but its replaced with question mark after saving to another location. 读取时,请查看下面显示的实体‐(-作为十六进制)的快照,但保存到另一个位置后,将其替换为问号。

While Reading as Inner XML 以内部XML读取时

作为内部XML读取时

While Reading as Inner Text 阅读为内文时

作为内文阅读时

After Saving XML File 保存XML文件之后

保存XML之后

EDIT 1 Below is my code 编辑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);

EDIT 2 My source file looks like below. 编辑2我的源文件如下所示。 I need to retain the entities as it is 我需要保留实体

在此处输入图片说明

The issue here seems to be the handling of encoding of entity references by the specific XmlWriter implementation internal to XmlDocument . 这里的问题似乎是XmlDocument内部的特定XmlWriter实现对实体引用编码的处理。

The issue disappears if you create an XmlWriter yourself - the unsupported character will be correctly encoded as an entity reference. 如果您自己创建XmlWriter ,问题将消失-不支持的字符将被正确编码为实体引用。 This XmlWriter is a different (and newer) implementation that sets an EncoderFallback that encodes characters as entity references for characters that can't be encoded. XmlWriter是一个不同的(以及更新的)实现,它设置一个EncoderFallback ,该编码器将字符编码为EncoderFallback编码的字符的实体引用。 Per the remarks in the docs, the default fallback mechanism is to encode a question mark. 根据文档中的备注,默认的后备机制是对问号进行编码。

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

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

As an aside, I'd recomment using the LINQ to XML XDocument API, it's much nicer to work with than the old creaky XmlDocument API. XDocument ,我建议使用LINQ to XML XDocument API,与旧的,笨拙的XmlDocument API一起使用要好得多。 And its version of Save doesn't have this problem, either! 而且其Save版本也不存在此问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM