Is your XML Fluent?

I’m currently developing a small reporting engine as an extension to an application I worked on earlier. The implementation works with generated XML and XSLT files. If there is anything i truly despise about this project is writing out XML to match a certain spec.

This is especially tedious when you start dealing with verbose XML structures. Well, a few days ago i think i found a really good solution to this painful ordeal. It’s a tiny little class that wraps System.XML namespace into an intuitive and easy fluent API. Introducing XMLOutput.

This little gem will let you turn this (Yes i copied it from Mark’s site)…

XmlDocument xd = new XmlDocument();  
xd.AppendChild(xd.CreateXmlDeclaration("1.0", "utf-8", ""));

XmlNode root = xd.CreateElement("root");  
xd.AppendChild(root);

XmlNode result = xd.CreateElement("result");  
result.InnerText = "true";

XmlAttribute type = xd.CreateAttribute("type");  
type.Value = "boolean";

result.Attributes.Append(type);  
root.AppendChild(result);  

Into this…

XmlOutput xo = new XmlOutput()  
    .XmlDeclaration()
    .Node("root").Within()
        .Node("result").Attribute("type", "boolean").InnerText("true");

I’ve tested this on fairly complex structures and this tiny class never failed me. I did, however, managed to find an inconvenience. While this API works great if you’re just outputting static content, things get a bit clunky when you need to say, loop through a collection of objects and generate nodes. To do this, you’d have to break out of your fluent method chaining. I made a small addition to the class by allowing the client to register a simple delegate in order to run complex logic without breaking fluent chaining.

public XmlOutput ExecuteAction(Action<XmlOutput> action)  
{
    action(this);

    return this;
}

We can now do something like this…

.Within()
    .ExecuteAction(act => {
        // Run custom action here    
    })
.EndWithin()