Why does getting elements from an XDocument result in zero?

Can someone explain to me why xml1.Element ("title") is correctly equal to " <title>Customers Main333</title>", but xml2.Element ("title") is surprisingly null , that is why I have to get the XML document as an element instead of a document to pull from it elements?

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>
+3
source share
3 answers

XDocument represents the entire document, not the root node . Use Rootto get the root element.

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

must work.

+9
source

, XDocument , , , . XElement .

+2

As I understand it, many DOM implementations as a document have a level above the root element, which allows the use of "Add", etc. You have a link to this level, there is no root element.

When analyzing only an element, this is not necessary or useful, therefore it is omitted.

You can use .Rootto get the root element.

0
source

Source: https://habr.com/ru/post/1714225/


All Articles