简体   繁体   中英

Getting Attribute's value from xml in c#

I have a LINQ expression which gets the XML attribute values from a xml file.

 var xml = XElement.Load(@"C:\\StoreServer1.xml");
 var query = from e in xml.Descendants("Groups")
             where int.Parse(e.Element("Store").Value) == 1500
             select e.Element("Store").Attribute("WeekDayStClose").Value;

And the xml file is:

enter<?xml version="1.0" encoding="utf-8" ?>
<Stores>
    <Groups Range="000"> 
        <Store WeekDayStClose="210" SatStClose="21" SunStClose="22">1500</Store>
        <Store WeekDayStClose="23" SatStClose="24" SunStClose="25">18</Store>
        <Store WeekDayStClose="23" SatStClose="24" SunStClose="25">19</Store>
    </Groups> 
</Stores>

I am only getting the attribute result (value) for first element of 1500. If I search same thing for 18 it doesn't return any result and no exception. Any help appreciated....Plz help!!!

You should be more granular, call sub Descendants with Store (XName):

    var xml = XElement.Load(@"C:\\New Folder\\StoreServer1.xml");
    var query = from e in xml.Descendants("Groups").Descendants("Store")
                where int.Parse(e.Value) == 18
                select e.Attribute("WeekDayStClose").Value;

Because now you're retrieving only the first Store of each Group which is 1500 .

Try this out:-

var xml = XElement.Load(@"C:\\StoreServer1.xml");
var query = xml.Descendants("Groups").Descendants("Store").Where(e => int.Parse(e.Value) == 18).Select(e=> e.Attribute("WeekDayStClose").Value);

Yes, you have a little error in your code: You are splitting your xml into group-elements (you have just one group). Then you check if the first store element has the value 1500 (you are not checking if the following store elements have maybe the value 1500)

You need to change your code into the following

        var query = from e in xml.Descendants("Store")
                    where int.Parse(e.Value) == 1500
                    select e.Attribute("WeekDayStClose").Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM