Created
February 18, 2012 21:32
-
-
Save NOtherDev/1861068 to your computer and use it in GitHub Desktop.
Loquacious XML builder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class NodeBuilder | |
{ | |
private readonly XmlDocument _doc; | |
private readonly XmlNode _node; | |
public NodeBuilder(XmlDocument doc, XmlNode node) | |
{ | |
_doc = doc; | |
_node = node; | |
} | |
public void SetAttribute(string name, string value) | |
{ | |
var attribute = _doc.CreateAttribute(name); | |
attribute.Value = value; | |
_node.Attributes.Append(attribute); | |
} | |
public XmlNode AddNode(string name) | |
{ | |
var newNode = _doc.CreateElement(name); | |
_node.AppendChild(newNode); | |
return newNode; | |
} | |
public void AddContent(string content) | |
{ | |
_node.AppendChild(_doc.CreateTextNode(content)); | |
} | |
} | |
public interface INode | |
{ | |
void Attr(string name, string value); | |
void Node(string name, Action<INode> action); | |
void Content(string content); | |
} | |
internal class NodeImpl : INode | |
{ | |
private readonly XmlDocument _doc; | |
private readonly NodeBuilder _nb; | |
public NodeImpl(XmlDocument doc, XmlNode node) | |
{ | |
_doc = doc; | |
_nb = new NodeBuilder(doc, node); | |
} | |
public void Attr(string name, string value) | |
{ | |
_nb.SetAttribute(name, value); | |
} | |
public void Node(string name, Action<INode> action) | |
{ | |
action(new NodeImpl(_doc, _nb.AddNode(name))); | |
} | |
public void Content(string content) | |
{ | |
_nb.AddContent(content); | |
} | |
} | |
public static class Xml | |
{ | |
public static string Node(string name, Action<INode> action) | |
{ | |
using (var stringWriter = new StringWriter()) | |
{ | |
var doc = new XmlDocument(); | |
var root = new NodeBuilder(doc, doc).AddNode(name); | |
action(new NodeImpl(doc, root)); | |
doc.WriteTo(new XmlTextWriter(stringWriter)); | |
return stringWriter.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment