But the direct child elements do have an empty xmlns attribute. How can I avoid that?
You specify the namespace for the child elements as well:
doc.Root.Add(new XElement(ns + "SomeChildElement"));
The point is that elements inherit the closest xmlns=...
namespace specification. When you just use new XElement("SomeChildElement")
that's actually creating an element with an empty namespace URI, so the xmlns=""
would be required in order to give it the right namespace. If you want:
<RootElement xmlns="http://mynamespace.de/test">
<SomeChildElement />
</RootElement>
Then you really want a SomeChildElement
element with the same namespace as the root element - which is what the code at the top of my answer will give you.
Note that you don't need the verbatim string literal for the namespace, by the way - a regular string literal is fine, as the URI doesn't contain any backslashes or new lines:
XNamespace ns = "http://mynamespace.de/test";