tags:

views:

44

answers:

1

Hi, I am trying to write a query expression to parse an XML tree, but without much luck.

The tree is as follows:

<item> 
    <itemInfo id="1965339" lang="en" key="title"> 
      <info>Octopuzzle&#xd;</info> 
    </itemInfo> 
    <itemInfo id="1965337" lang="en" key="longDescription"> 
      <info>&quot;In Octopuzzle you play the Octopus on a mission! Escape the dangerous reef, and save it in the process. To do so you’ll have to make it through 20 challenging levels.&#xd;
The game offers a real brain teasing levels packed with interactive sea creatures and objects that will keep you hooked for more. Along the way you’ll have shooting challenges, cannons to jump from, meet armoured fish, and many more surprises the deep-sea has to offer.&#xd;
Are you ready for the deep-sea puzzle adventure?&#xd;
&quot;&#xd;</info> 
    </itemInfo> 
    <itemInfo id="1965335" lang="en" key="shortDescription"> 
      <info>In Octopuzzle you play the Octopus on a mission! Escape the dangerous reef, and save it in the process. To do so you’ll have to make it through 20 challenging levels.&#xd;</info> 
    </itemInfo> 
</item>

I load into into a XElement without any problems.

What I need to do is get the values of title, short description, and long description respectively for a given value of the lang attribute, in this case en.

Can anyone help? Thanks

A: 

Sure, something like:

private string GetValue(XElement element, string language, string key)
{
    return element.Elements("itemInfo")
                  .Where(x => (string) x.Attribute("lang") == language)
                  .Where(x => (string) x.Attribute("key") == key)
                  .Select(x => (string) x.Element("info"))
                  .FirstOrDefault();
}
...
string title = GetValue(item, "en", "title");
string longDescription = GetValue(item, "en", "longDescription");
string shortDescription = GetValue(item, "en", "shortDescription");

If you've already got the relevant item element, I don't think you really want a query expression; if you're querying over multiple elements you might. For example:

var query = from item in doc.Descendants("item")
            select new {
                Title = GetValue(item, "en", "title"),
                LongDescription = GetValue(item, "en", "longDescription"),
                ShortDescription = GetValue(item, "en", "shortDescription");
            };
Jon Skeet
Thanks for the answer Jon, I think that would work fine. I am in fact querying over several items. Just wondering, is there any way to do some sort of nested query within the itemInfo XElements? So have a select going through every item, and then for every time having a select within the itemInfo XElements?Thanks
Steve Kiss
@Steve: I'm not sure what you mean, I'm afraid. Could you give an example (by editing the question)?
Jon Skeet
Jon, it's alright. I think your solution will do the trick. ThanksSteve
Steve Kiss