Search code examples
c#xmlxml-namespacesxmldocument

How to create root node with xmlns:xsi but no prefix?


What's the proper way to create a root node without the prefix, but have it display xmlns:xsi="blah"? Basically I want something like this:

<EDSCrate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="EDS_Crate_2010-02-10.xsd" version="0.95">
    <Whatever>
    </Whatever>
</EDSCrate>

However, I've tried many ways, it just won't give me a simple node without the namespace, and even if it does, it doesn't give me the proper xmlns:xsi in the attribute.

I'd like to avoid any hack like overriding the ToString and replacing the text myself in the XmlWriter.

string uri = "http://www.w3.org/2001/XMLSchema-instance";

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));

nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsi", uri);

XmlElement root = doc.CreateElement("EDSCrate", uri);
// at this point, it already added xmlns="http://www.w3.org/2001/XMLSchema-instance" without me doing anything
root.RemoveAllAttributes();
// but i want xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"!!
root.SetAttribute("xmlns:xsi", uri);
root.SetAttribute("xsi:noNamespaceSchemaLocation", "EDS_Crate_2010-02-10.xsd");

Solution

  • string uri = "http://www.w3.org/2001/XMLSchema-instance";
    
    var doc = new XmlDocument();
    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
    
    var root = doc.CreateElement("EDSCrate");
    doc.AppendChild(root);
    root.AppendChild(doc.CreateElement("Whatever"));
    
    var attr = doc.CreateAttribute("xsi", "noNamespaceSchemaLocation", uri);
    attr.InnerText = "EDS_Crate_2010-02-10.xsd";
    root.SetAttributeNode(attr);
    
    root.SetAttribute("version", "0.95");