views:

177

answers:

3

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>
A: 

As I understand it, many DOM implementations as a document have a level above the root element, allowing for consistent "Add" etc. You have a reference to this level, no the root element.

When parsing just an element, this isn't necessary or useful, so is omitted.

You should be able to use .Root to get the root element.

Marc Gravell
+1  A: 

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.

Andrew Hare
+3  A: 

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.

SealedSun