You must add "type"
to the actual namespace URI, "http://www.w3.org/2001/XMLSchema-instance"
, not to the namespace prefix, like so:
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var element = new XElement("Details", new XAttribute(ns + "type", "SomeStuff"));
Also, you can completely skip adding an XAttribute
for the namespace URI/prefix mapping, XmlWriter
will do it automatically as long as XElement.Name.Namespace
and XAttribute.Name.Namespace
were set correctly during construction.
This is one of the things that makes LINQ to XML simpler than XmlDocument
-- you can ignore prefixes entirely and work only with real namespace URIs, which is both simpler and more likely to result in correct code that does not depend on the choice of namespace prefix. Though if you really want to manually specify the prefix for cosmetic reasons see How can I write xml with a namespace and prefix with XElement? which indicates the correct method is:
var element = new XElement("Details", new XAttribute(XNamespace.Xmlns + "p2", ns), new XAttribute(ns + "type", "SomeStuff"));
which results in:
<Details xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" p2:type="SomeStuff" />
Sample .Net fiddle here.