Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getting Elements from an XDocument result in null?

Can anyone explain to me why xml1.Element("title") correctly equals "<title>Customers Main333</title>" but xml2.Element("title") surprisingly equals null, i.e. why do I have to get the XML document as an element instead of a document in order to pull elements out of it?

var xml1 = XElement.Load(@"C:\\test\\smartForm-customersMain.xml");
var xml2 = XDocument.Load(@"C:\\test\\smartForm-customersMain.xml");

string title1 = xml1.Element("title").Value;
string title2 = xml2.Element("title").Value;

XML:

<?xml version="1.0" encoding="utf-8" ?>
<smartForm idCode="customersMain">
    <title>Customers Main333</title> 
    <description>Generic customer form.</description>
    <area idCode="generalData" title="General Data">
        <column>
            <group>
                <field idCode="anrede">
                    <label>Anrede</label>
                </field>
                <field idCode="firstName">
                    <label>First Name</label>
                </field>
                <field idCode="lastName">
                    <label>Last Name</label>
                </field>
            </group>
        </column>
    </area>
    <area idCode="address" title="Address">
        <column>
            <group>
                <field idCode="street">
                    <label>Street</label>
                </field>
                <field idCode="location">
                    <label>Location</label>
                </field>
                <field idCode="zipCode">
                    <label>Zip Code</label>
                </field>
            </group>
        </column>
    </area>
</smartForm>
like image 644
Edward Tanguay Avatar asked Dec 29 '25 22:12

Edward Tanguay


2 Answers

The XDocument represents the whole document, not the root node. Use Root to get the root element.

var title = xml2.Root.Element("title").Value; 

should work.

like image 179
Christian Klauser Avatar answered Dec 31 '25 16:12

Christian Klauser


This is because XDocument has an outermost layer that requires you to drill past to get to the elements. An XElement targets the actual element itself.

like image 44
Andrew Hare Avatar answered Dec 31 '25 16:12

Andrew Hare