I have a function which generates xml for a list object:
public XDocument ToXML()
{
foreach (var row in this)
{
var xml = row.ToXml();
template.Root.Add(xml);
}
return template;
}
The template.ToString() reads: <RootElement xmlns="urn:testTools">
The xml reads: <Example><SubElement>testData</SubElement></Example>
After the add function has executed the template.ToString() reads: <RootElement xmlns="urn:testTools"><Example xmlns=""><SubElement>testData</SubElement></Example>
So for some reason there was an empty namespace added, how can i prevent it from doing so?
Set the namespace on the Example and SubElement elements to the same as the RootElement. It is adding the xmlns="" to clear the namespace for these elements.
Here is an example that outputs xml without empty namespaces. Notice the bizarre Linq-centric syntax rootNamespace + "MyElementName", which is the secret. This is the same namespace as the whole document, thus no xmlns addition is necessary. This is concatenating an XNamespace + a string, which is a "+" overload that works for Linq and that Linq knows how to deal with. (Without Linq it could be a compile error to concatenate a string and a non string type). Note this was executed against a C# project file which is a handy Xml file. Output it to a console or a richtextbox control. Then take out the "rootNamespace +" and notice the difference.
I solved it by replacing the elements with an regex. Foole's solution didn't work, because i didn't always now the exact namespace at that point in code.
So here's my dirty hack that works:
It could be that your root needs to be closed properly: