Question How do I create an xml file and also use the xml in my program?

groadsvb

Well-known member
Joined
Nov 13, 2006
Messages
75
Programming Experience
Beginner
I hope I got my question correct as I am new to everything .net. I need to serialize a class so that I can write it to an xml document but I also need to use the xml so I can pass it to another process. I am trying to use an system.io.streamwriter because the system.io.stringwriter uses utf-16 instead of utf-8. Can someone give me hints as what I need to use to serialize the class so that I can write the xml file but use the xml string in my program to pass toanother process. Thanks.

here is a some test code that I have thrown together to work out my issue:
dim sw as system.io.stringwriter
xslsizer = New System.Xml.Serialization.XmlSerializer(GetType(Class1))
xslsizer.Serialize(sw, theclass)
Dim str As String = sw.ToString
Dim f2 As New Form2
f2.TextBox1.Text = str
f2.Show()
 
Last edited:
system.io.stringwriter uses utf-16 instead of utf-8
That is a bit of a misconseption, because .Net strings are always Unicode (UTF-16). What it seems you're actually referring to here is the encoding attribute of the xml content. Without writing to a file or other output stream you can use a MemoryStream, with that no encoding is specified in xml, which has the meaning of default Utf-8 encoding.
Dim mem As New IO.MemoryStream
xslsizer.Serialize(mem, theclass)
Dim str As String = System.Text.Encoding.UTF8.GetString(mem.ToArray)

If you also put a XmlWriter.Create into that, and by the default XmlWriterSettings, the xml content will also include the encoding attribute and it is thus set to Utf-8.
Dim mem As New IO.MemoryStream
Dim writer = Xml.XmlWriter.Create(mem)
xslsizer.Serialize(writer, theclass)
Dim str As String = System.Text.Encoding.UTF8.GetString(mem.ToArray)
 
Back
Top