gpt4 book ai didi

c# - 如何在不转义字符的情况下保存 XML?

转载 作者:行者123 更新时间:2023-11-30 12:33:26 28 4
gpt4 key购买 nike

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

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

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

另一个例子:<myElement>• bullet</myElement> ,我的处理将其更改为 <myElement>&#8226; bullet</myElement>它被保存到 <myElement>&amp;#8226; bullet</myElement> .我想要输出到文件的是 <myElement>&#8226; bullet</myElement>形式。

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

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

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

为了保留格式等,它可能会演变成自定义 XmlWriter。

感谢所有有用的建议。

最佳答案

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

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);

这无需取消编码或绕过编码功能即可工作。

关于c# - 如何在不转义字符的情况下保存 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9285909/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com