我想序列化一個對象,我必須將一個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
感謝國旗@Default!不知道它被稱爲是,但它做到了! –
np,我知道它的原因是因爲我之前有過你的確切問題:) – Default