2009-12-18 41 views
2

我的應用程序從外部試圖XML保存到磁盤(當它進入XmlWriter爲什麼.NET XML API不能保護我不受空字符的影響?

System.ArgumentException : '.', hexadecimal value 0x00, is an invalid character. 
時收到字符串和構建XML文檔

string fromOutside = "\0"; 
XAttribute a = new XAttribute(fromOutside); 

當屬性值包含空字符,然後我得到異常

即使SecurityElement類不利於

Assert.IsFalse(SecurityElement.IsValidAttributeValue("\0")); 

什麼是最好的從字符串構造XML文檔的方式,可能包含像空字符等無效字符?

回答

2

您不能轉義非打印字符,如NULL,因爲沒有爲它們定義的等效轉義字符。除非你有十六進制或Base64編碼的片段,否則你不能表示它。因此,您可以使用Base64對字符串進行編碼或確保它不包含非打印字符。

string fromOutside = "\0"; 
string base64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(fromOutside)); 
XAttribute a = new XAttribute("id", base64Encoded); 
+1

所以在我的情況下,唯一的辦法就是分析字符串並刪除空人物,不是嗎? :-( –

+0

不,你也可以Base64編碼字符串:'Convert.ToBase64String(Encoding.UTF8.GetBytes(fromOutside))' –

+1

Base64對我來說不是一個選項,因爲我必須保持字符串在結果中可讀XML 。字符串的例子可以是「\ 0My \ 0 fancy val \ 0ue \ 0 \ 0 \ 0」。 –

相關問題