您可以通过指定 xmlns 属性显式覆盖此行为:
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>
默认情况下,行为是内嵌指定 xmlns。
XNamespace ns = "urn:test";
new XDocument (
new XElement ("root",
new XElement (ns + "foo",
new XElement (ns + "bar", "content")
))
).Dump ();
给出输出:
<root>
<foo xmlns="urn:test">
<bar>content</bar>
</foo>
</root>
因此,默认行为是您想要的行为,除非已经定义了命名空间:
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>