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>
Chris chilvers
source share