Adding schemaLocation attribute to XElement in LINQ to SQL

I have spent a bit of time trying to figure out how to generate an XML document with all the XML namespace paraphernalia – including schema location. I got stuck trying to create the xmlns:xsi attribute – LINQ to XML kept creating a namespace alias for me and calling it p1 like so:

<rootNode p1:xsi="http://www.w3.org/2001/XMLSchema-instance" p1="http://www.foo.bar" xmlns="http://www.foo.bar">
</rootNode>

Turns out the answer is pretty simple. I was correct in my assumption that in order to create a namespace alias one must simply add an attribute to the node. However the xmlns namespace is special and one cannot use the string xmlns or use the default namespace. Instead one must use XNamespace.Xmlns – like so: new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"). Here is complete code:

XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
            XNamespace defaultNamespace = XNamespace.Get("http://www.foo.bar");
            XElement root = new XElement(defaultNamespace + "rootNode",
                new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
                new XAttribute(xsi + "noNamespaceSchemaLocation", @"..\path\to\schema.xsd"));
The above code will generate this:
<rootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="..\path\to\schema.xsd" xmlns="http://www.foo.bar" >
</rootNode>

/***********************
******* Comments *******
***********************/

  1. Sourabh

    Thanks buddy !

  2. I was wondering how to do this and sort of did a Dope when I saw how simple it was.

    One thing, you don’t need to do a XNamespace.Get() for the xsi namespace since it is already in the XNamespace.Xmlns constant.

    So adding the xsi attribute becomes:

    new XAttribute(XNamespace.Xmlns + “xsi”, XNamespace.Xmlns.NamespaceName),

    Michael

  3. Nevermind, my mistake, disregard my post.

Leave a Reply