Connecting Tech Pros Worldwide Forums | Help | Site Map

XmlDocument question

Brecht Yperman
Guest
 
Posts: n/a
#1: Nov 12 '05
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>"?
(or some other way, without XmlDocument?)

Derek Harmon
Guest
 
Posts: n/a
#2: Nov 12 '05

re: XmlDocument question


"Brecht Yperman" <BrechtYperman@discussions.microsoft.com> wrote in message
news:F3E280DE-394E-4159-9196-D0F5141628BF@microsoft.com...[color=blue]
> doc.Save(textWriter);
> ...
> returns "<item><name></name></item>"
> Is there a way to make it return "<item><name /></item>"?[/color]

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


Closed Thread


Similar .NET Framework bytes