0

I'm trying to serialize an object I have to an XmlDocument (which is then saved to a file). The problem is that some hex characters seem to be placed in front of the actual xml when I view the file in hex representation (using UltraEdit). These characters are being read by another program I have, which is causing issues.

The first line contains this (notice leading ):

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

I'm not sure why I'm getting those characters.
The code that creates the document:

' 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)  

And then I create the file here:

Using xw As XmlTextWriter = New XmlTextWriter(myFile, New UTF8Encoding(True))
    xw.Formatting = Formatting.Indented
    xw.Indentation = 1
    xw.IndentChar = " "
    xd.Save(xw)
End Using
Broots Waymb
  • 4,713
  • 3
  • 28
  • 51

1 Answers1

0

Not sure how helpful this will be but i have seen this before were the encoding of the file is not what you expect it to be. Even though you have set it to UTF8 the generated file comes out as something else.

Check the generated file in a text editor that shows you the encoding and see if it is what expect.

The issue that i had was some characters in the original file that was forcing the save function to compensate and change the encoding.

  • It's called a [BOM](https://en.wikipedia.org/wiki/Byte_order_mark) and it is not related to incorrect encoding. – default Jul 27 '16 at 17:15