質問

I want to set the namespace of the root element in a XML file which works:

XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
XNamespace ns = @"http://mynamespace.de/test";
doc.Add(new XElement(ns + "RootElement"));
doc.Root.Add(new XElement("SomeChildElement"));

But the direct child elements do have an empty xmlns attribute. How can I avoid that? I only want the namespace set in the root element.

役に立ちましたか?

解決

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";
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top