Given the following xml:
<root xmlns="http://tempuri.org/myxsd.xsd">
<node name="mynode" value="myvalue" />
</root>
And given the following code:
string file = "myfile.xml"; //Contains the xml from above
XDocument document = XDocument.Load(file);
XElement root = document.Element("root");
if (root == null)
{
throw new FormatException("Couldn't find root element 'parameters'.");
}
If the root element contains the xmlns attribute then the variable root is null. If I remove the xmlns attribute then root is NOT null.
Can anyone explain why this is?
When you declare your root element like
<root xmlns="http://tempuri.org/myxsd.xsd">this means that your root element all of its descendants are inhttp://tempuri.org/myxsd.xsdnamespace. By default namespace of an element has an empty namespace andXDocument.Elementlooks for elements without namespace. If you want to access an element with a namespace you should explicitly specify the namespace.For your case