In C#, is there a way to generate an XDocument usi

2019-04-07 07:30发布

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.

1条回答
Animai°情兽
2楼-- · 2019-04-07 08:29

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> 
查看更多
登录 后发表回答