364,085 Members | 5289 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

Force XmlSerializer to use explicit closing tags for zero-length strings?

scott.ballard@gmail.com
P: n/a
scott.ballard@gmail.com
Greetings,

I am using the .Net Framework XmlSerializer to serialize a class that
contains some string properties. The problem is that when a string
contains a zero-length string ("") it is serialized as:

<foo />

When what I would really like is:

<foo></foo>

Now I know the former is well-formed and all, but I really need the
explicit closing tag. The XML file will be read by another system (out
of my control) that requires the explicit closing tag. Any ideas here?
Thank you.

Regards,

Scott Ballard

Nov 12 '05 #1
Share this Question
Share on Google+
1 Reply


Derek Harmon
P: n/a
Derek Harmon
<scott.ballard@gmail.com> wrote in message news:1110988470.845630.79610@z14g2000cwz.googlegro ups.com...[color=blue]
> The problem is that when a string contains a zero-length string ("") it is serialized as:
> <foo />
> When what I would really like is:
> <foo></foo>[/color]

Scott,

You can control this by subclassing XmlTextWriter to inter-
cept all calls to WriteFullEndElement( ) and substitute a call
to WriteEndElement( ) instead. WriteEndElement( ) is smart
enough to know whether it must write a full end tag or not.

- - - XmlTextWriterEE.cs (complete)
using System;
using System.IO;
using System.Xml;

namespace Derek.Xml
{
/// <summary>
/// Wrapper that forces more compact empty element end
/// tags to be written whenever possible.
/// </summary>
public class XmlTextWriterEE : XmlTextWriter
{
public XmlTextWriterEE( TextWriter sink) : base( sink) {*;}
public override void WriteFullEndElement( ) {
base.WriteEndElement( );
}
}
}
- - -

In your case you would use this class in the project and wrap
the TextWriter you may already using in an XmlTextWriterEE
when calling Serialize( ),

serializer.Serialize( new XmlTextWriterEE( destTextWriter), obj);


Derek Harmon


Nov 12 '05 #2

Post your reply

Help answer this question



Didn't find the answer to your .NET Framework question?

You can also browse similar questions: .NET Framework