Wednesday, June 2, 2010

Force XML closing tag when using XML Serializer (in VB.NET)

To force an xml closing tag explicitly when using XML serializer (Kind of the vb version of this)

http://bytes.com/topic/net/answers/178893-force-xmlserializer-use-explicit-closing-tags-zero-length-strings


I wanted to serialize an empty object to 

xmlSerialize.serialize produced 

Without manually fixing up the produced xml, I decided to do like the above article and override the default WriteEndElement behaviour. Unfortunately the application is in vb (It turned out I didn't need to do it, but I got it working anyway )

So here's a rough conversion:

Imports System.Xml.Serialization

Public Class XMLTextWriterEE
    Inherits XmlTextWriter

    Public Sub New(ByVal sink As TextWriter)

        MyBase.New(sink)
    End Sub

    '''
    ''' Wrapper that forces more compact empty element end tags to be written whenever possible.
    '''
    Public Overrides Sub WriteEndElement()

        MyBase.WriteFullEndElement()


    End Sub

To use you just do the normal serialize call, but pass the stringWriter to your overridden property:
serializer.Serialize( new XmlTextWriterEE( destTextWriter), obj)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.