I’m having some issues with namespaces in LINQ. So going off of MSDN’s Tutorial we can do the following to add namespaces to an XML document with LINQ:
// Create an XML tree in a namespace.
XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
new XElement(aw + "Child", "child content")
);
Console.WriteLine(root);
Which will give you the XML:
<Root xmlns="http://www.adventure-works.com">
<Child>child content</Child>
</Root>
But what I want to do is this:
XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Roots");
XElement child = new XElement("Child", "child content");
root.Add(child);
Console.WriteLine(root);
But this gives me the following xml:
<Root xmlns="http://www.adventure-works.com">
<Child xmlns="">child content</Child>
</Root>
The problem is I don’t want the xmlns="" in my child elements (EDIT: I don’t want any namespaces in my child elements), I want it to look just like the first way produces it. I am building a fairly large XML file so I can’t add all the elements in the same declaration and need to be able to use the Add and SetAttributeValue methods of multiple XElements still having an xmlns on the first element. Any ideas how I can accomplish this?
Thanks!
This behavior is fundamental to the XML information set. The effect of the
xmlnsdeclaration is scoped to all child content; since you did not specify a namespace for the child element, the standard behavior is to place it in the unnamed namespace. In order to nest an element in an unnamed namespace inside of one that declares a default namespace, thexmlns=''declaration is required to reset the default namespace to unnamed.To summarize, based on your edit:
xmlns=''is required by the XML Namespaces specification in order to override the namespace declared in the document element.xmlns=''stuff) in your child elements, you need to make sure the same namespace is added to the names of all of them in code.There is no way I know of to make an
XElementautomatically inherit the namespace of its parent. After you are done building the DOM, though, you can always postprocess it to set one namespace everywhere with something similar to this:I don’t believe doing this is advisable for anything other than throwaway code, though, since it will likely have untoward effects on maintainability. A number of XML documents I’ve had to deal with mix namespaces, and “smashing” namespaces like the above code snippet does would clobber the semantics of a mixed-namespace document.