2014-03-14 20 views
1

我的目標是在不丟失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 documentationThe 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來做到這一點?

+0

如果你只是通過控制檯檢查,你可能要檢查Console.OutputEncoding。 – tweellt

+0

@tweellt但是我的目標是將XML序列化爲能夠在ASCII中生存的東西(這意味着無論Console.OutputEncoding在英文系統上設置的編碼如何,它都能存活)。 – binki

回答

4

您可以使用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> 
+0

你能幫我怎麼把ä轉換成&#x00E4;通過使用xmldocument庫 –

+1

@Karthick這是一個奇怪的願望...在任何情況下,你應該問一個單獨的問題,並說明爲什麼它對你的文本很重要(絕對沒有區別於XML的觀點)。 –

+0

是的兩者是相同的,但我需要保留,因爲它是在源XML文件。 –

相關問題