I'm simply trying to make my XML a bit tidier and less bulky. I know in C# one can do something like this:
XNamespace ds = "http://schemas.microsoft.com/ado/2007/08/dataservices";
new XElement(ds + "MyDumbElementName", "SomethingStupid");
And get an XML simliar to this:
<root>
<MyDumbElementName xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
SomethingStupid
</MyDumbElementName>
</root>
Instead of something like this:
<root xmlns:ds="http://schemas.microsoft.com/ado/2007/08/dataservices">
<ds:MyDumbElementName>
SomethingStupid
</ds:MyDumbElementName>
</root>
Obviously the second version is much prettier, easier to read, and compact. Is there any way to generate an XDocument equivalent of the compact version, without calling Parse("...")?
You may decide to take a risk and answer "No", in which case I believe the fair thing to do is wait for other people to answer, and if no-one gives a decent answer I'll accept your "No", otherwise if someone does provide an answer, I'll mark the "No" down. I hope that seems fair to you too.
EDIT: Perhaps I should be a bit more specific and say that I want to be able to use multiple name spaces, not just one.
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
These are the type of operators that act upon just a single operand for producing a new value. All the unary operators have equal precedence, and their associativity is from right to left. When we combine the unary operator with an operand, we get the unary expression.
You can explicitly override this behaviour 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 the behaviour is to specify the xmlns in-line.
XNamespace ns = "urn:test";
new XDocument (
new XElement ("root",
new XElement (ns + "foo",
new XElement (ns + "bar", "content")
))
).Dump ();
Gives the output:
<root>
<foo xmlns="urn:test">
<bar>content</bar>
</foo>
</root>
So the default behaviour is your desired behaviour, except when 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With