I have this
XNamespace ns = "http://something0.com";
XNamespace xsi = "http://something1.com";
XNamespace schemaLocation = "http://something3.com";
XDocument doc2 = new XDocument(
new XElement(ns.GetName("Foo"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi.GetName("schemaLocation"), schemaLocation),
new XElement("ReportHeader", GetSection()),
GetGroup()
)
);
It gives
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader xmlns="">
...
</ReportHeader>
<Group xmlns="">
...
</Group>
</Foo>
But I wan’t this result, how can it be done? (Notice the xmlns=""is missing..)
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader>
...
</ReportHeader>
<Group>
...
</Group>
</Foo>
Your problem here is that you are setting the default namespace for the document to “http://something0.com”, but then appending elements that are not in this namespace – they are in the empty namespace.
Your document states it has a default namespace of xmlns=”http://something0.com”, but then you append elements which are in the empty namespace (because you didn’t supply their namespace when you appended them) – so they are all getting explicitly marked with xmlns=” to show they are not in the default namespace of the document.
This means there are two solutions to getting rid of the xmlns=””, but they have different meanings:
1) If you mean you definitely want the
xmlns="http://something0.com"at the root element (specifying the default namespace for the document) – then to “disappear” the xmlns=”” you need to you need to supply this namespace when creating the elements:2) If these elements are not meant to be in the namespace
“http://something0.com”, then you mustn’t add it as the default at
the top of the document (the xmlns=”http://something0.com” bit on
the root element).
The sample output you expect, suggests the former of these two choices.