2014-09-26 50 views
2

我有一個二維數組(矩陣),我編碼爲xml使用XmlSerializer。當我反序列化字符串時,我有時會得到錯誤。
像下面這樣。它說XML文檔不好,因爲它包含一個十六進制值0x00是否存在不可(可)序列化的「kill-strings」?

System.InvalidOperationException: Fehler im XML-Dokument (1,18449). --- 
    System.Xml.XmlException: '.', hexidezimaler Wert 0x00, ist ein ungültiges 
    Zeichen. Zeile 1, Position 18449. 
bei System.Xml.XmlTextReaderImpl.Throw(Exception e) 
bei System.Xml.XmlTextReaderImpl.Throw(String res, String[] args) 
bei System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String[] args) 


Possible solution

錯誤的部分是這樣的:

<anyType xsi:type="xsd:string">&#x0;</anyType> 

這是否意味着&#x0;不是序列化的或者是我試圖序列壞的字符串? 我該怎麼做才能避免出現此異常?


我的代碼:

// serialize 

StringBuilder builder = new StringBuilder(512 * 1024); 
StringWriter writer = new StringWriter(builder); 
object[][] array = table.ToArray(true); 
try 
{ 
    new XmlSerializer(typeof(object[][])).Serialize(writer, array); 
    return builder.Replace(Environment.NewLine, string.Empty).ToString(); 
} 
catch (Exception exception) { return exception.Message; } 
finally 
{ 
    writer.Close(); 
    writer.Dispose(); 
} 

// de-serialize 

StringReader reader = new StringReader(xml); 
object[][] array = (object[][])new XmlSerializer(typeof(object[][])).Deserialize(reader); 
reader.Close(); 
reader.Dispose(); 
+0

XML不允許值爲0的實體。[spec](http://www.w3.org/TR/REC-xml/#charsets) – knittl 2014-09-26 13:16:39

+0

NUL teminator字符[XML中根本不合法] (http://www.w3.org/TR/REC-xml/#NT-Char) – pln 2014-09-26 13:17:39

+0

[The Invulnerable XMLException]的可能重複(http://stackoverflow.com/questions/9798033/the-invulnerable-xmlexception) – InferOn 2014-09-26 13:18:22

回答

3

是的,有一個whole bunch of characters未在XML文檔中允許的,ASCII碼0就是其中之一。 (感謝knittl和pln提供spec中的位置)。

是否有你的字符串包含十六進制值0x00的原因?這似乎是一個字符串具有的奇怪值,因爲它被用作終止字符。

我建議看一看,如果字符串確實需要包含這些字符,則您有一個選項是在序列化期間將數據轉換爲base64,並在反序列化期間將其轉換回來。

+0

好的暗示爲base64解決方法! – helb 2014-09-26 14:17:21