Tuesday, 25 November 2014

Encoding XML in Vb.net for SOAP Web Service



Hey all I am trying to get this code below to be encoded into UTF8 but it seems to have an error when doing so:



Dim myStringWriter As New StringWriter()
Dim writer As XmlTextWriter = New XmlTextWriter(myStringWriter)
Dim settings As New XmlWriterSettings()

Private Function getDetails() As String
writer.Formatting = Formatting.Indented
settings.Encoding = System.Text.Encoding.UTF8
settings.Indent = True
settings.ConformanceLevel = ConformanceLevel.Document
writer = XmlWriter.Create(myStringWriter, settings)
getResults(Searcher.FindAll, Searcher)

'more code here....

'write out XML
writer.Flush()
myXmlString = myStringWriter.ToString()
myStringWriter.Close()
writer.Close()
End Function

Private Sub getResults(ByVal results As SearchResultCollection, ByVal Searcher As DirectorySearcher)
writer.WriteStartDocument(True)
writer.Formatting = Formatting.Indented
writer.Indentation = 2
writer.WriteStartElement("EmployeeInformation")

'more code here....
writer.WriteEndElement()
writer.WriteEndElement()
writer.WriteEndDocument()
End Sub


The error is:



Additional information: Unable to cast object of type 'System.Xml.XmlWellFormedWriter' to type 'System.Xml.XmlTextWriter'.



On the line:



writer = XmlWriter.Create(myStringWriter, settings)


without defining the Encode.UTF8 it works fine but puts this as the XML string:



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


Which should be:



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


I'm not quite sure how to go about fixing this so any help would be great!


No comments:

Post a Comment