Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

XmlBuilder

3.40/5 (5 votes)
20 Oct 2008CPOL2 min read 1   173  
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)