16

I have an C# class that I would like to serialize using XMLSerializer. But I would like to have it serialized to a XMLElement or XMLDocument. Is this possible or do I have to serialize it to a String and then parse the string back to a XMLDocument?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konstantin
  • 3,626
  • 2
  • 33
  • 45

3 Answers3

39

I had this problem too, and Matt Davis provided a great solution. Just posting some code snippets, since there are a few more details.

Serializing:

public static XmlElement SerializeToXmlElement(object o)
{
    XmlDocument doc = new XmlDocument();

    using(XmlWriter writer = doc.CreateNavigator().AppendChild())
    {
        new XmlSerializer(o.GetType()).Serialize(writer, o);
    }

    return doc.DocumentElement;
}

Deserializing:

public static T DeserializeFromXmlElement<T>(XmlElement element)
{
    var serializer = new XmlSerializer(typeof(T));

    return (T)serializer.Deserialize(new XmlNodeReader(element));
}
Dave Andersen
  • 5,337
  • 3
  • 30
  • 29
  • 2
    Warning, microperf nit: Better to use new XmlNodeReader() around the XmlNode as the XmlReader source when deserializing instead of converting it to a string and back. The string conversion uses about double the wallclock time and some more memory (admittedly, not much under normal circumstances, but the NodeReader approach feels cleaner too). – nitzmahone Sep 24 '12 at 20:08
  • Thanks! I didn't even know that reader existed. It definitely does seem cleaner that way. – Dave Andersen Sep 25 '12 at 16:49
11

You can create a new XmlDocument, then call CreateNavigator().AppendChild(). This will give you an XmlWriter you can pass to the Serialize method that will dump into the doc root.

nitzmahone
  • 13,720
  • 2
  • 36
  • 39
-1
Public Shared Function ConvertClassToXml(source As Object) As XmlDocument
    Dim doc As New XmlDocument()
    Dim xmlS As New XmlSerializer(source.GetType)
    Dim stringW As New StringWriter
    xmlS.Serialize(stringW, source)
    doc.InnerXml = stringW.ToString
    Return doc
End Function
Public Shared Function ConvertClassToXmlString(source As Object) As String
    Dim doc As New XmlDocument()
    Dim xmlS As New XmlSerializer(source.GetType)
    Dim stringW As New StringWriter
    xmlS.Serialize(stringW, source)
    Return stringW.ToString
End Function
Public Shared Function ConvertXmlStringtoClass(Of T)(source As String) As T
    Dim xmlS As New XmlSerializer(GetType(T))
    Dim stringR As New StringReader(source)
    Return CType(xmlS.Deserialize(stringR), T)
End Function
Public Shared Function ConvertXmlToClass(Of T)(doc As XmlDocument) As T
    Dim serializer = New XmlSerializer(GetType(T))
    Return DirectCast(serializer.Deserialize(doc.CreateNavigator.ReadSubtree), T)
End Function