1

I've been having some trouble writing queries in LINQ to grab the data i need from an XML file.

The XML file set up looks like this

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

I'm trying to get the value of the filepath node where id ="display"

var displaySettingsQuery = (from n in _XML.Descendants("Study").Descendants("Multi")
                                    where n.Element("Multi").Attribute("id").Value == "display"
                                    select n.Element("filepath").Value);

This doesn't seem to work because the Element() method only grabs the first instance of "Multi". However if I use Elements(), I get a syntax error, since Elements is a Ienumerable, so I can't call attribute directly. How would I go about iterating through the "Multi" collection in order to do my comparison?

Thanks for the assistance.

4
  • is Id attribute for the filepath element or Multi element? in xml, it is for filepath but your query expects it to be of Multi. Commented May 20, 2015 at 20:13
  • The id attribute is for the filepath element, sorry about that. After changing Multi to filepath, in my where clause, it still doesn't seem to be returning any results. Commented May 20, 2015 at 20:15
  • And you have one single Multi element? Commented May 20, 2015 at 20:16
  • There are multiple Multi elements. I'll edit my question to clarify. Commented May 20, 2015 at 20:17

1 Answer 1

1

This can be easier if you make from clause to return <filepath> elements instead of <Multi>, because you only care about <filepath> in the where and select clause :

var displaySettingsQuery = (from n in _XML.Descendants("Study")
                                          .Elements("Multi")
                                          .Elements("filepath")
                            where n.Attribute("id").Value == "display"
                            select n.Value);
Sign up to request clarification or add additional context in comments.

Comments

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.