-
-
Save yjagota/1939312 to your computer and use it in GitHub Desktop.
Loquacious XML builder
This file contains 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; | |
} | |
internal XmlNode AddNode(string name, Action<INode> action, INode nodeImpl) | |
{ | |
var newNode = _doc.CreateElement(name); | |
_node.AppendChild(newNode); | |
var oldNode = _node; | |
_node = newNode; | |
action(nodeImpl); | |
_node = oldNode; | |
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 NodeBuilder _nb; | |
public NodeImpl(XmlDocument doc, XmlNode node) | |
{ | |
_nb = new NodeBuilder(doc, node); | |
} | |
public void Attr(string name, string value) | |
{ | |
_nb.SetAttribute(name, value); | |
} | |
public void Node(string name, Action<INode> action) | |
{ | |
_nb.AddNode(name, action, this); | |
} | |
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