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

橙三吉。 提交于 2019-12-04 05:00:01

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> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!