I have posted several times in the past on Fluent Interfaces. I think about Fluent Interfaces much in the same way I think about recursive functions, that is they are not for everything, but when you find the situation that warrants them then they are a great fit. On the other hand when you try to use them for the wrong situations they are an awful fit.
In the past, I've found at various orgs that i am constantly creating an XmlUtils() class to handle the creation of documents in a more tighter syntax. Back in those days, I was unaware of Fluent Interfaces and how they could possibly tackle this problem
Well today I just came across Mark Resmussen's sweet FI for defining an XmlDocument, and it looks like a great fit.
XML we are trying to create
<?xml version="1.0" encoding="utf-8"?>
<root>
<result type="boolean">true</result>
</root>
Using System.Xml
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);
New way using Mark's FI
XmlOutput xo = new XmlOutput()
.XmlDeclaration()
.Node("root").Within()
.Node("result").Attribute("type", "boolean").InnerText("true");
ANY QUESTIONS?
Posted
Tue, Feb 26 2008 7:41 AM
by
Glenn Block