如何在不转义字符的情况下保存XML

本文关键字:情况下 保存 XML 转义字符 | 更新日期: 2023-09-27 18:24:29

在我的C#应用程序中,XML数据可能包含已预处理的任意元素文本,因此(除其他外)非法字符已转换为转义(XML字符实体编码)形式。

示例:<myElement>this & that</myElement>已转换为<myElement>this &amp; that</myElement>

问题是,当我使用XmlTextWriter保存文件时,'&'正在被重新转义到<myElement>this &amp;amp; that</myElement>中。我不想要额外的&amp在字符串中。

另一个例子:<myElement>• bullet</myElement>,我的处理将其更改为<myElement>&#8226; bullet</myElement>,并将其保存到<myElement>&amp;#8226; bullet</myElement>。我只想输出到文件中的是<myElement>&#8226; bullet</myElement>表单

我在各种XmlWriter等上尝试了各种选项,但似乎无法获得正确输出的原始字符串。为什么XML解析器不能识别&没有重写已经有效的转义?

更新:经过更多的调试,我发现每当元素文本字符串(实际上包括元素标记、名称、属性等的所有字符串)被System.xml下一个名为XmlCharType的内部类复制到.net xml对象数据中时(CDATA是一个例外),它们都会被编码。因此问题与XmlWriters无关。看起来解决这个问题的最好方法是在数据输出时取消转义,或者使用以下方法:

string output = System.Net.WebUtility.HtmlDecode(xmlDoc.OuterXml);

它可能会演变成一个自定义的XmlWriter,以保留格式等。

谢谢大家的建议。

如何在不转义字符的情况下保存XML

好的,这是我提出的解决方案:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
namespace YourName {
    // Represents a writer that makes it possible to pre-process 
    // XML character entity escapes without them being rewritten.
    class XmlRawTextWriter : System.Xml.XmlTextWriter {
        public XmlRawTextWriter(Stream w, Encoding encoding)
            : base(w, encoding) {
        }
        public XmlRawTextWriter(String filename, Encoding encoding)
            : base(filename, encoding) {
        }
        public override void WriteString(string text) {
            base.WriteRaw(text);
        }
    }
}

然后像使用XmlTextWriter:一样使用它

        XmlRawTextWriter rawWriter = new XmlRawTextWriter(thisFilespec, Encoding.UTF8);
        rawWriter.Formatting = Formatting.Indented;
        rawWriter.Indentation = 1;
        rawWriter.IndentChar = ''t';
        xmlDoc.Save(rawWriter);

这在不需要取消编码或破解编码功能的情况下工作。

改为调用xmlwriter.writeraw。但检查字符是否有效还不够聪明。因此,您必须自己检查,否则将生成一个无效的xml。