When I try to parse XDocument from text, I can get the default namespace like this:
var xmlDocument1 = XDocument.Parse("<root xmlns='http://somenamespace'></root>");
var xmlNamespace1 = xmlDocument1.Root.GetDefaultNamespace().NamespaceName; // somenamespace
However, if I try to create XDocument manually, I'm getting an empty value:
var xmlRoot2 = new XElement(XName.Get("root", "http://somenamespace"));
var xmlDocument2 = new XDocument(xmlRoot2);
var xmlNamespace2 = xmlDocument2.Root.GetDefaultNamespace().NamespaceName; // is empty
I expect xmlNamespace2 to be "http://somenamespace". Is there anything I'm doing wrong?
Edit: The answer in suggested duplicate doesn't solve my problem, even if I use the function suggested here: How to set the default XML namespace for an XDocument I will still get the empty namespace. Here is the solution from the linked question:
class Program
{
static void Main(string[] args)
{
var xmlRoot = new XElement(XName.Get("root"));
var xmlDocument = new XDocument(xmlRoot);
SetDefaultXmlNamespace(xmlRoot, "http://somenamespace");
var xmlNamespace = xmlDocument.Root.GetDefaultNamespace().NamespaceName; // is empty
}
public static void SetDefaultXmlNamespace(XElement xelem, XNamespace xmlns)
{
if (xelem.Name.NamespaceName == string.Empty)
xelem.Name = xmlns + xelem.Name.LocalName;
foreach (var e in xelem.Elements())
SetDefaultXmlNamespace(e, xmlns);
}
}
The default namespace is still empty.