如何将XmlDocument.Save()转换为encoding="us-ascii"使用数字字符实

本文关键字:quot us-ascii 数字字符 encoding XmlDocument Save 转换 | 更新日期: 2023-09-27 17:50:22

我的目标是在不丢失Unicode字符的情况下获得XML的二进制缓冲区(在本例中MemoryStream.ToArray()将生成byte[])。我希望XML序列化器使用数字字符引用来表示在ASCII中无效的任何内容。到目前为止,我有:

using System;
using System.IO;
using System.Text;
using System.Xml;
class Program
{
    static void Main(string[] args)
    {
        var doc = new XmlDocument();
        doc.LoadXml("<x>“∞π”</x>");
        using (var buf = new MemoryStream())
        {
            using (var writer = new StreamWriter(buf, Encoding.ASCII))
                doc.Save(writer);
            Console.Write(Encoding.ASCII.GetString(buf.ToArray()));
        }
    }
}

上面的程序产生如下输出:

$ ./ConsoleApplication2.exe
<?xml version="1.0" encoding="us-ascii"?>
<x>????</x>

我弄清楚了如何告诉XmlDocument.Save()使用encoding="us-ascii" -通过将TextStream.Encoding设置为Encoding.ASCIITextStream交给它。文档上写的是The encoding on the TextWriter determines the encoding that is written out。但我如何告诉它,我希望它使用数字字符实体,而不是默认的有损行为?我已经测试了doc.Save(Console.OpenStandardOutput())将期望的数据(没有XML声明)写入具有所有正确字符的UTF-8,因此我知道doc包含我希望序列化的信息。这只是一个问题,找出正确的方式来告诉XML序列化器,我想要encoding="us-ascii"与字符实体…

我明白,编写既支持encoding="us-ascii"又支持<π/>等结构的XML文档可能是不平凡的(我认为这可能只适用于外部文档类型定义)。是的,我试过了,只是为了好玩。但是我认为在ASCII XML文档中输出非ASCII字符的实体以支持在unicode不友好的环境中保存内容属性值字符数据是很常见的。我认为表示Unicode字符的数字字符引用类似于使用base64来保护blob,同时保持内容更具可读性。我如何在。net中做到这一点?

如何将XmlDocument.Save()转换为encoding="us-ascii"使用数字字符实

您可以使用XmlWriter:

  var doc = new XmlDocument();
    doc.LoadXml("<x>“∞π”</x>");
    using (var buf = new MemoryStream())
    {
        using (var writer =  XmlWriter.Create(buf, 
              new XmlWriterSettings{Encoding= Encoding.ASCII}))
        {
            doc.Save(writer);
        }
        Console.Write(Encoding.ASCII.GetString(buf.ToArray()));
    }

输出:

<?xml version="1.0" encoding="us-ascii"?><x>&#x201C;&#x221E;&#x3C0;&#x201D;</x>