0

I am writing an xml file to post to a OTA API I see a difference in the output if I write it in string or in file. If I write it in string I see a different encoding It looks like when I write to string setting is not working. Any help? I simplify code placing 2 buttons button 2 writes in file one button 3 in string. You see codes are the same. Any suggestion? Thx

Output button 2 in file first line

?xml version="1.0" encoding="UTF-8" standalone="true"?>

Output button 3 in string

?xml version="1.0" encoding="utf-16" standalone="yes"?>

code

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Dim settings As New XmlWriterSettings
    Dim nomefile As String
    Dim stxmlns As String
    stxmlns = "http://www.testconnect.com/EQC/AR/2011/06"
    settings.Indent = True ' true stabilisce di andare a capo quando cambi elemento
    settings.NewLineOnAttributes = True
    settings.Encoding = Encoding.UTF8
    nomefile = "C:\documenti\test.xml"
    Dim wr As XmlWriter = XmlWriter.Create(nomefile, settings)
    wr = creawritertest(wr)
    wr.Flush()
    MsgBox("OK")
End Sub


Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
    Dim settings As New XmlWriterSettings
    Dim sw As New StringWriter()
    Dim stxmlns As String
    stxmlns = "http://www.testconnect.com/EQC/AR/2011/06"
    settings.Indent = True ' true stabilisce di andare a capo quando cambi elemento
    settings.NewLineOnAttributes = True
    settings.Encoding = Encoding.UTF8
    Dim wr As XmlWriter = XmlWriter.Create(sw, settings)
    wr = creawritertest(wr)
    wr.Flush()
    mess.Text = sw.ToString
End Sub

Private Function creawritertest(wr As XmlWriter) As XmlWriter
    Dim stxmlns As String
    stxmlns = "http://www.testconnect.com/EQC/AR/2011/06"

    wr.WriteStartDocument(True)

    wr.WriteStartElement("AvailRateUpdateRQ", stxmlns)
    wr.WriteEndElement()
    Return wr
End Function
Andrea
  • 11,801
  • 17
  • 65
  • 72
lucullo08
  • 41
  • 1
  • 10
  • Well .NET `String` are sequences of UTF-16 encoded characters so that is why writing to a StringWriter gives you that encoding. It is possible to override that if really needed but in general using a certain encoding makes sense if you write to a file or to a stream, not when you write to a string. – Martin Honnen Nov 07 '15 at 10:46
  • Also see http://stackoverflow.com/questions/9459184/why-is-the-xmlwriter-always-outputing-utf-16-encoding which shows how to override the encoding if needed (code there is in C# but of course you can do the same in VB). – Martin Honnen Nov 07 '15 at 10:49
  • When you "save as" file using notepad you will notice that there is an option to save file as either UTF8 or Unicode. So XmlWriter is using the file setting and not the setting you are specifying. – jdweng Nov 07 '15 at 10:57

0 Answers0