Search code examples
xelement

XElement null when attributes exist


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?


Solution

  • 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 in http://tempuri.org/myxsd.xsd namespace. By default namespace of an element has an empty namespace and XDocument.Element looks for elements without namespace. If you want to access an element with a namespace you should explicitly specify the namespace.

    var xdoc = XDocument.Parse(
    "<root>" +
        "<child0><child01>Value0</child01></child0>" +
        "<child1 xmlns=\"http://www.namespace1.com\"><child11>Value1</child11></child1>" +
        "<ns2:child2 xmlns:ns2=\"http://www.namespace2.com\"><child21>Value2</child21></ns2:child2>" +
    "</root>");
    
    var ns1 = XNamespace.Get("http://www.namespace1.com");
    var ns2 = XNamespace.Get("http://www.namespace2.com");
    
    Console.WriteLine(xdoc.Element("root")
                          .Element("child0")
                          .Element("child01").Value); // Value0
    
    Console.WriteLine(xdoc.Element("root")
                          .Element(ns1 + "child1")
                          .Element(ns1 + "child11").Value); // Value1
    
    Console.WriteLine(xdoc.Element("root")
                          .Element(ns2 + "child2")
                          .Element("child21").Value); // Value2
    

    For your case

    var ns = XNamespace.Get("http://tempuri.org/myxsd.xsd");
    xdoc.Element(ns + "root").Element(ns + "node").Attribute("name")