tahasozgen
tahasozgen

Reputation: 491

Getting the root element of xml file in linq

I am using linq. Here is my document structure:

<t totalWord="2" creationDate="15.01.2016 02:33:37" ver="1">
    <k kel_id="1000">
        <kel>7</kel>
        <kel_gs>0</kel_gs>
        <kel_bs>0</kel_bs>
        <km>Ron/INT-0014</km>
        <kel_za>10.01.2016 02:28:05</kel_za>
        <k_det kel_nit="12" kel_res="4" KelSID="1" >
            <kel_ac>ac7</kel_ac>
        </k_det>
    </k>
    <k kel_id="1001">
        <kel>whitte down</kel>
        <kel_gs>0</kel_gs>
        <kel_bs>0</kel_bs>
        <km>Ron/INT-0014</km>
        <kel_za>15.01.2016 02:33:37</kel_za>
        <k_det kel_nit="12" kel_res="4" KelSID="1">
            <kel_ac>to gradually make something smaller by making it by taking parts away</kel_ac>
            <kel_kc>cut down</kel_kc>
            <kel_oc>The final key to success is to turn your interviewer into a champion: someone who is willing to go to bat for you when the hiring committee meets to whittle down the list.</kel_oc>
            <kel_trac >adım adım parçalamak</kel_trac>
        </k_det>
    </k>
</t>

This is a dictionary. t is root. k is word. When a new word arrives, totalword attribute and creationDate shall update accordingly. I have to get t node, get its attribute and save it. I have written the code above:

XDocument xdoc = XDocument.Load(fileName);
XElement rootElement = xdoc.Root;
XElement kokNode = rootElement.Element("t");
XAttribute toplamSayi = kokNode.Attribute("totalWord");

kokNode comes null. How can I solve it? Thanks in advance.

Upvotes: 0

Views: 5268

Answers (3)

Yacoub Massad
Yacoub Massad

Reputation: 27861

"totalWord" is an attribute of the root element which is t, not an attribute of k. So simply get the attribute from the root element like this:

XDocument xdoc = XDocument.Load(fileName);

XElement rootElement = xdoc.Root;

XAttribute toplamSayi = rootElement.Attribute("totalWord");

Upvotes: 0

Charles Mager
Charles Mager

Reputation: 26213

xdoc.Root will return the root element, which is your t element in this case.

rootElement.Element("t") will therefore return null as t has no child t element.

Either use xdoc.Root or xdoc.Element("t"), i.e.:

var tomplamSayi = xdoc.Root.Attribute("totalWord")

or:

var tomplamSayi = xdoc.Element("t").Attribute("totalWord")

Upvotes: 1

Webster
Webster

Reputation: 1153

try this :

string totalword;
foreach (XElement x in xdoc.Descendants("t")){
   totalword= x.Attribute("totalword").Value.ToString().Trim(); // Get the totalword attribute's value
}

Upvotes: 0

Related Questions