Archive for December, 2007

using a default xml namespace with the XElement class

No Comments »Written on December 2nd, 2007 by
Categories: Uncategorized

I just upgraded all of the xml parsing code in Noma to use the new classes in the System.Xml.Linq namespace, which btw are MUCH easier to use than the old-school XmlDocument/XmlElement/... set of classes. Anyway, i have a lot of tests that create xml elements in memory so the parsing can be tested on them. Now, all of those elements should of course use the correct xml namespace.

With the new XElement class, this is already much easier to do than it was with the XmlElement class. But, if you're creating a hell of a lot of XElement instances that all need to use the same namespace, you can very easily extend the XElement class to set the correct namespace by default:

    public class NXElement : XElement

    {

        public NXElement(string name, params object[] objects)

            : base(Constants.XmlNamespace + name, objects) {}

 

        public NXElement(string name, object parameter)

            : base(Constants.XmlNamespace + name, parameter) {}

 

        public NXElement(string name)

            : base(Constants.XmlNamespace + name) {}

    }

And now i can create nested XML elements that use the correct namespace just like this:

            XElement element = new NXElement(Elements.List,

                                            new NXElement(Elements.OneToMany,

                                                           new XAttribute(Attributes.Class, "ClassName")));