我的目標是在不丟失Unicode字符的情況下獲取XML的二進制緩衝區(MemoryStream.ToArray()
將產生byte[]
)。我期望XML序列化程序使用數字字符引用來表示任何在ASCII中無效的內容。到目前爲止,我有:如何使用數字字符實體而不是問號對XmlDocument.Save()進行編碼=「us-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"
-by與TextStream.Encoding
集交給它TextStream
到。 The documentation說The encoding on the TextWriter determines the encoding that is written out
。但是我怎麼能告訴它,我希望它使用數字字符實體而不是它的默認有損行爲?我已經測試了doc.Save(Console.OpenStandardOutput())
將所需的數據(沒有XML聲明)寫成UTF-8與所有正確的字符,所以我知道doc
包含我希望序列化的信息。這只是一個找出正確的方式來告訴我要encoding="us-ascii"
與字符實體XML序列化的事情......
我明白,這可能是不平凡的編寫都是encoding="us-ascii"
和支持像<π/>
結構的XML文檔(我認爲這可能只適用於外部文檔類型定義,是的,I have tried just for fun。)。但我認爲在ASCII XML文檔中輸出非ASCII字符的實體非常普遍,以支持在Unicode不友好的環境中保存內容和屬性值字符數據。我認爲表示Unicode字符的數字字符引用類似於使用base64保護blob,同時保持內容更具可讀性。我如何使用.NET來做到這一點?
如果你只是通過控制檯檢查,你可能要檢查Console.OutputEncoding。 – tweellt
@tweellt但是我的目標是將XML序列化爲能夠在ASCII中生存的東西(這意味着無論Console.OutputEncoding在英文系統上設置的編碼如何,它都能存活)。 – binki