Click here to Skip to main content
15,890,690 members
Articles / Programming Languages / XML
Article

XmlBuilder

Rate me:
Please Sign up or sign in to vote.
3.40/5 (5 votes)
20 Oct 2008CPOL2 min read 36.1K   173   12   5
Wraps an XmlDocument to simplify formatting flat data into XML

Introduction

This article describes my XmlBuilder class, which I use whenever I have some simple information that I need to format as XML.

Background

There are many times when one needs to write some simple information; such as when writing events to a log file. The simplest technique is to just write it:

C#
MyLog.WriteLine ( message ) ;

This technique can be extended to include some meta-information, such as time and source:

C#
MyLog.WriteLine 
( 
    "{0:yyyy-MM-ddTHH:mm:sszzz} {1}: {2}" 
,
    System.DateTime.Now
,
    sourcename
,
    message
) ;

That's the sort of log file I used for years, but then XML became popular and I saw how it could be used for this task. The simplest way to modify the previous code to write XML with the time and source as attributes is:

C#
MyLog.WriteLine 
( 
    "<Message Time=\"{0:yyyy-MM-ddTHH:mm:sszzz}\" Source=\"{1}\">{2}</Message>" 
,
    System.DateTime.Now
,
    sourcename
,
    System.Web.HttpUtility.HtmlEncode ( message )
) ;

Note the use of HtmlEncode to protect against message text that includes characters that would result in non-well-formed XML. The developer should likewise protect sourcename, but I decided not to do so here, to make the point that sometimes we forget or think it's not important.

This technique works well, but the code is difficult to read and maintain. After writing code like this in several places (not just for logging), I finally decided to find a better way.

XmlDocument

Using an XmlDocument to handle the details of producing well-formed XML makes the programmer's job easier. I then progressed to this technique:

C#
System.Xml.XmlDocument doc = new System.Xml.XmlDocument() ;
 
doc.AppendChild ( doc.CreateElement ( "Message" ) ) ;
doc.DocumentElement.Attributes.Append ( doc.CreateAttribute ( "Time"   ) ) ;
doc.DocumentElement.Attributes.Append ( doc.CreateAttribute ( "Source" ) ) ;
 
...
 
doc.DocumentElement.InnerText = message ;
doc.DocumentElement.Attributes [ "Time"   ].Value = System.DateTime.Now.ToString (
    "yyyy-MM-ddTHH:mm:sszzz" ) ;
doc.DocumentElement.Attributes [ "Source" ].Value = sourcename ;
 
MyLog.WriteLine ( doc.OuterXml ) ;

However, I wanted to encapsulate this technique to provide simple access to only the one element and its attributes.

XmlBuilder

XmlBuilder is the result of this progression.

For brevity, in the following snippets I've removed the comments and exception handling.

XmlBuilder contains only one field, the XmlDocument:

C#
namespace PIEBALD.Types
{
    public class XmlBuilder
    {
        private readonly System.Xml.XmlDocument document ;

        ...
    }
}

Constructors

The primary constructor takes the name of the element and an optional list of attributes to create.

C#
public XmlBuilder
(
    string          Name
,
    params string[] Attributes
)
{
    this.document = new System.Xml.XmlDocument() ;

    this.document.AppendChild
    (
        this.document.CreateElement ( Name )
    ) ;

    if ( Attributes != null )
    {
        foreach ( string att in Attributes )
        {
            this [ att ] = null ;
        }
    }

    return ;
}

I also included a constructor that can perform a shallow copy of an existing XmlDocument:

C#
public XmlBuilder
(
    System.Xml.XmlDocument XmlDocument
)
{
    this.document = new System.Xml.XmlDocument() ;

    this.document.AppendChild ( this.document.CreateElement
    (
        XmlDocument.DocumentElement.Name
    ) ) ;

    if ( XmlDocument.DocumentElement.FirstChild is System.Xml.XmlText )
    {
        this.document.DocumentElement.InnerText =
            XmlDocument.DocumentElement.FirstChild.Value ;
    }

    foreach ( System.Xml.XmlAttribute att in XmlDocument.DocumentElement.Attributes )
    {
        this [ att.Name ] = att.Value ;
    }

    return ;
}

Note that text will only be copied from the first child if it is an XmlText node.

Properties

The name and innertext of the element are accessible with the following properties:

C#
public virtual string
Name
{
    get
    {
        return ( this.document.DocumentElement.Name ) ;
    }
}
C#
public virtual string
InnerText
{
    get
    {
        return ( this.document.DocumentElement.InnerText ) ;
    }

    set
    {
        this.document.DocumentElement.InnerText = value ;

        return ;
    }
}

Indexer

Attributes are created and accessed with the following indexer:

C#
public virtual string
this
[
    string Attribute
]
{
    get
    {
        string result = null ;

        if ( this.document.DocumentElement.HasAttribute ( Attribute ) )
        {
            result = this.document.DocumentElement.Attributes [ Attribute ].Value ;
        }

        return ( result ) ;
    }

    set
    {
        if ( !this.document.DocumentElement.HasAttribute ( Attribute ) )
        {
            this.document.DocumentElement.Attributes.Append
            (
                this.document.CreateAttribute ( Attribute )
            ) ;
        }

        this.document.DocumentElement.Attributes [ Attribute ].Value = value ;

        return ;
    }
}

Methods

There are only two methods:

C#
public virtual System.Xml.XmlNode
RemoveAttribute
(
    string Attribute
)
{
    return ( this.document.DocumentElement.Attributes.RemoveNamedItem ( Attribute ) ) ;
}
C#
public override string
ToString
(
)
{
    return ( this.document.DocumentElement.OuterXml ) ;
}

Using the Code

A class that uses an XmlBuilder may create and configure a static readonly instance so it's always available:

C#
private static readonly PIEBALD.Types.XmlBuilder xmlbuilder = 
new PIEBALD.Types.XmlBuilder 
( 
    "Message" 
,
    "Time"
,
    "Source"
) ;

An example of a method that uses an XmlBuilder:

C#
private static void
LogMessage
(
    string Message
,
    string SourceName
)
{
    lock ( xmlbuilder )
    {
        xmlbuilder.InnerText    = Message ;
        xmlbuilder [ "Time"   ] = System.DateTime.Now.ToString (
            "yyyy-MM-ddTHH:mm:sszzz" ) ;
        xmlbuilder [ "Source" ] = SourceName ;
 
        MyLog.WriteLine ( xmlbuilder.ToString() ) ;
    }

    return ;
}

History

2008-10-18 First submitted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology

Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.

OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]

"Typing is no substitute for thinking." -- R.W. Hamming

"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup

ZagNut’s Law: Arrogance is inversely proportional to ability.

"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon

"linq'ish" sounds like "inept" in German -- Andreas Gieriet

"Things would be different if I ran the zoo." -- Dr. Seuss

"Wrong is evil, and it must be defeated." –- Jeff Ello

"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw

“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

"Omit needless local variables." -- Strunk... had he taught programming

Comments and Discussions

 
Question[Message Deleted] Pin
Pelletier.JY21-Apr-09 8:44
Pelletier.JY21-Apr-09 8:44 
AnswerRe: Problem with using this control in a Master/content page solution using DataSource binding. Pin
PIEBALDconsult21-Apr-09 14:41
mvePIEBALDconsult21-Apr-09 14:41 
QuestionSample-Project? Pin
Mr.PoorEnglish20-Oct-08 22:47
Mr.PoorEnglish20-Oct-08 22:47 
AnswerRe: Sample-Project? Pin
PIEBALDconsult21-Oct-08 4:00
mvePIEBALDconsult21-Oct-08 4:00 
AnswerRe: Sample-Project? Pin
PIEBALDconsult21-Oct-08 4:17
mvePIEBALDconsult21-Oct-08 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.