2016-07-27 57 views
0

我想序列化一個對象,我必須將一個XmlDocument(然後保存到一個文件)。問題是,當我以十六進制表示查看文件(使用UltraEdit)時,一些十六進制字符似乎放在實際的xml前面。這些字符正在被我擁有的另一個程序讀取,這是造成問題的原因。xml開頭的意外前導十六進制字符

第一行包含這個(通知領先):

<?xml version="1.0" encoding="utf-8"?> 

我不知道爲什麼我得到這些字符。
創建該文件的代碼:

' At this point, I have an object called newObj that has mostly string/integer fields. 
' It is non-null as populated with the correct data. 

xd = New XmlDocument 

Dim xs As XmlSerializer = New XmlSerializer(GetType(MyObj)) 
Dim result As String = String.Empty 
Using ms As MemoryStream = New MemoryStream() 
    xs.Serialize(ms, newObj) 

    ms.Position = 0 
    result = New StreamReader(ms).ReadToEnd() 
End Using 

xd.LoadXml(result) 

然後,我在這裏創建文件:

Using xw As XmlTextWriter = New XmlTextWriter(myFile, New UTF8Encoding(True)) 
    xw.Formatting = Formatting.Indented 
    xw.Indentation = 1 
    xw.IndentChar = " " 
    xd.Save(xw) 
End Using 
+0

感謝國旗@Default!不知道它被稱爲是,但它做到了! –

+0

np,我知道它的原因是因爲我之前有過你的確切問題:) – Default

回答

0

不知道如何有幫助這將是,但我已經看到了這之前,該文件的編碼不是你期望的那樣。即使您已將其設置爲UTF8,生成的文件也會以其他方式出現。

在顯示編碼的文本編輯器中檢查生成的文件,看看它是否符合期望。

我遇到的問題是原始文件中的一些字符迫使保存功能來補償和更改編碼。

+0

它被稱爲[BOM](https://en.wikipedia.org/wiki/Byte_order_mark),它與不正確的編碼無關。 – Default

相關問題