0

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!!!

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You used e.Element("Store") instead of Descendants("Store") because Element Gets the first (in document order) child element with the specified XName. (source: MSDN)
1

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.

Comments

0

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;

2 Comments

There are only 1 Stores
My mistake, i meant to write "Store"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.