Click here to Skip to main content
Licence CPOL
First Posted 20 Oct 2008
Views 12,779
Downloads 67
Bookmarked 11 times

XmlBuilder

By | 20 Oct 2008 | Article
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:

MyLog.WriteLine ( message ) ;

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

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:

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:

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:

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.

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:

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:

public virtual string
Name
{
    get
    {
        return ( this.document.DocumentElement.Name ) ;
    }
}
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:

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:

public virtual System.Xml.XmlNode
RemoveAttribute
(
    string Attribute
)
{
    return ( this.document.DocumentElement.Attributes.RemoveNamedItem ( Attribute ) ) ;
}
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:

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

An example of a method that uses an XmlBuilder:

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)

About the Author

PIEBALDconsult

Software Developer (Senior)

United States United States

Member

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
 
---------------
 
"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
 

"Omit needless local variables." -- Strunk... had he taught programming
 
"DON'T BE LIBERAL IN WHAT YOU ACCEPT!"
 
"Software Engineers don't have Trophy Wives; they have Presentation Layers."
 
"We learn more from our mistakes than we do from getting it right the first time."
 
"I'm an old dog and I like old tricks."
 
"Sometimes the envelope pushes back and sometimes you get a really nasty paper cut."
 
"A method shall have one and only one return statement."
 
My first rule of debugging: "If you get a different error message, you're making progress."
 
My golden rule of database management: "Do not unto others' databases as you would not have done unto yours."
 
My general rule of software development: "Design should be top-down, but implementation should be bottom-up."
 
"Today's heresy is tomorrow's dogma."
or
"Today's dogma is yesterday's heresy."
 
"The registry is evil."
 
"Every tool is a hammer."

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Question[Message Deleted] Pinmemberjy_p8:44 21 Apr '09  
AnswerRe: Problem with using this control in a Master/content page solution using DataSource binding. PinmemberPIEBALDconsult14:41 21 Apr '09  
QuestionSample-Project? PinmemberMr.PoorEnglish22:47 20 Oct '08  
AnswerRe: Sample-Project? PinmemberPIEBALDconsult4:00 21 Oct '08  
AnswerRe: Sample-Project? PinmemberPIEBALDconsult4:17 21 Oct '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 20 Oct 2008
Article Copyright 2008 by PIEBALDconsult
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid