In C #, is there a way to generate an XDocument using a short prefix instead of the full namespace for each node?

I'm just trying to make my XML a little tidier and less cumbersome. I know that in C # you can do something like this:

XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices"; new XElement(ds + "MyDumbElementName", "SomethingStupid"); 

And get XML-simliar for this:

 <root> <MyDumbElementName xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices"> SomethingStupid </MyDumbElementName> </root> 

Instead of this:

 <root xmlns:ds="http://schemas.microsoft.com/ado/2007/08/dataservices"> <ds:MyDumbElementName> SomethingStupid </ds:MyDumbElementName> </root> 

Obviously, the second version is much more beautiful, easier to read and compact. Is there a way to generate the XDocument equivalent for the compact version without calling Parse ("...")?

You can take the risk and answer “No,” in which case I believe that it is a fair thing to wait until other people answer, and if no one gives a decent answer, I will accept your “No”, otherwise, if anyone it will provide an answer, I will say “No.” I hope this is also true.

EDIT: Perhaps I should be more specific and say that I want to be able to use multiple namespaces, not just one.

+7
source share
1 answer

You can explicitly override this behavior by specifying the xmlns attribute:

 XNamespace ns = "urn:test"; new XDocument ( new XElement ("root", new XAttribute (XNamespace.Xmlns + "ds", ns), new XElement (ns + "foo", new XAttribute ("xmlns", ns), new XElement (ns + "bar", "content") )) ).Dump (); <root xmlns:ds="urn:test"> <foo xmlns="urn:test"> <bar>content</bar> </foo> </root> 

By default, behavior should indicate xmlns in a string.

 XNamespace ns = "urn:test"; new XDocument ( new XElement ("root", new XElement (ns + "foo", new XElement (ns + "bar", "content") )) ).Dump (); 

Gives output:

 <root> <foo xmlns="urn:test"> <bar>content</bar> </foo> </root> 

So the default behavior is your desired behavior, unless the namespace is already defined:

 XNamespace ns = "urn:test"; new XDocument ( new XElement ("root", new XAttribute (XNamespace.Xmlns + "ds", ns), new XElement (ns + "foo", new XElement (ns + "bar", "content") )) ).Dump (); <root xmlns:ds="urn:test"> <ds:foo> <ds:bar>content</ds:bar> </ds:foo> </root> 
+10
source

All Articles