diff --git a/src/DynamicBuilder/Xml.cs b/src/DynamicBuilder/Xml.cs index ee7c026..89fcf57 100644 --- a/src/DynamicBuilder/Xml.cs +++ b/src/DynamicBuilder/Xml.cs @@ -298,6 +298,7 @@ public class Xml : DynamicObject { // Uses the System.Xml.Linq types for internally modeling the XML XDocument root = new XDocument(); + private XNamespace _xNamespace; // holds the current container being worked on in cases of nesting XContainer current; @@ -331,29 +332,57 @@ public static Action Fragment(Action fragmentBuilder) return fragmentBuilder; } - /// - /// Alternate syntax for generating an XML object via this static factory - /// method instead of expliclty creating a "dynamic" in client code. - /// - /// - /// - public static Xml Build(Action builder) - { - if (builder == null) { throw new ArgumentNullException("builder"); } - - var xbuilder = new Xml(); - builder(xbuilder); - return xbuilder; - } + /// + /// Alternate syntax for generating an XML object via this static factory + /// method instead of expliclty creating a "dynamic" in client code. + /// + /// + /// Default namespace + /// + public static Xml Build( Action builder, string xNamespace = null ) + { + XNamespace ns = xNamespace; + return Build(builder, ns); + } + + /// + /// Alternate syntax for generating an XML object via this static factory + /// method instead of expliclty creating a "dynamic" in client code. + /// + /// + /// Default namespace + /// + public static Xml Build(Action builder, XNamespace xNamespace) + { + if( builder == null ) { throw new ArgumentNullException( "builder" ); } + + var xbuilder = new Xml( xNamespace ); + builder( xbuilder ); + return xbuilder; + } /// /// Constructs a new Dynamic XML Builder /// - public Xml() + /// Default namespace + public Xml(string xNamespace = null) { - current = root; + current = root; + if( xNamespace != null ) + _xNamespace = xNamespace; } + /// + /// Constructs a new Dynamic XML Builder + /// + /// Default namespace + public Xml( XNamespace xNamespace ) + { + current = root; + if( xNamespace != null ) + _xNamespace = xNamespace; + } + /// /// Converts dynamically invoked method calls into nodes. /// example 1: xml.hello("world") becomes world @@ -417,7 +446,7 @@ public void Tag(string tagName, params object[] args) }); // make a new element for this Tag() call - var element = new XElement(tagName); + var element = new XElement( tagName ); current.Add(element); // if a fragment delegate was passed for building inner nodes @@ -453,6 +482,10 @@ public void Tag(string tagName, params object[] args) } }); } + + // if no xmlns attribute is given then set the default namespace if the default namespace is set + if( _xNamespace != null && (attributes == null || attributes.GetType().GetProperties().Any(p => p.Name == "xmlns") ) ) + element.Name = _xNamespace + element.Name.ToString(); // if a fragment delegate was passed for building inner nodes // now go ahead and execute the delegate, and then set the current outer parent