简体   繁体   中英

C# XAttribute that is not a namespace

I'm writing a XML document using the XDocument class in C#.

Attempting to get this output:

<Details xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" p2:type="SomeStuff"></Details>

This is what I've tried, but it throws an exception because of the ":"

XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";

...

new XElement("Details", new XAttribute(XNamespace.Xmlns + "p2", ns), new XAttribute("p2:type", "SomeStuff"),

What is the proper way to achieve the desired output?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM