all groups > dotnet xml > january 2005 >
You're in the

dotnet xml

group:

XmlDocument question


XmlDocument question Brecht Yperman
1/28/2005 5:03:10 AM
dotnet xml:
Hi,

I'd like to implement the following feature, but I don't know how:
When I read in a document with 'empty' elements, i'd like them to be
'compressed'.

e.g.:
....
doc.LoadXml("<item><name></name></item>");
doc.Save(textWriter);
....

returns "<item><name></name></item>"
Is there a way to make it return "<item><name /></item>"?
Re: XmlDocument question Derek Harmon
1/28/2005 10:40:48 PM
[quoted text, click to view]

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
(it must write the full end tag if the element was not empty).

- - - 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're already using in an XmlTextWriterEE
when calling Save( ),

doc.Save( new XmlTextWriterEE( textWriter));

XmlElement also has an IsEmpty property you can set (make
sure the element has no child nodes before setting it to true,
though, because it will remove any child nodes). This may
be more convenient if you're walking over the XmlDocument
anyway, or want to selectively write compact tags.


Derek Harmon

AddThis Social Bookmark Button