using IXmlSerializable to create XmlDocument

olsonpm

Well-known member
Joined
Aug 24, 2010
Messages
46
Programming Experience
Beginner
I'm stumped and have been working on this for the past 4 hours. It seems simple but here are my issues.

I start with a class 'Car' which implements IXmlSerializable. Then I try using a method 'getXML()' to return an XmlDocument. Now with this, i can write it to a file no problem using the following code.

VB.NET:
Public Function getXML() As XmlDocument
    Dim xmlDoc As New XmlDocument()
    Dim bufStream As New BufferedStream(New MemoryStream())
    Dim serializer As New XmlSerializer(GetType(Car), "http://www.w3.org/2001/XMLSchema-instance")
    Dim writer As New StreamWriter("SerialXML.xml", Nothing)
    serializer.Serialize(writer, Me)
    writer.Close()
    xmlDoc.Load("SerialXML.xml")
    Return (xmlDoc)
End Function

The problem is that writing to a file is a complete hack to what I actually want to do. Now I've tried plenty of times using streams in order to skip the writing to a file, but I keep getting miscellaneous errors (mainly an empty stream resulting in a "root element not found" exception). Could someone please push me in the right direction in this pretty simple problem?

thanks,
Phil
 
"root element not found" exception
Often caused by writing to stream, which then is positioned to end, and when XmlDocument attempts to read it immediately reaches end of stream and never finds the document source. This should work, notice setting MemoryStream position to 0:
VB.NET:
Dim doc As New Xml.XmlDocument
Dim ser As New Xml.Serialization.XmlSerializer(Me.GetType)
Using mem As New IO.MemoryStream
    ser.Serialize(mem, Me)
    mem.Position = 0
    doc.Load(mem)
End Using
Return doc
 
Back
Top