tags:

views:

40

answers:

2

I can't quite get my query correct. Given this XML:

<?xml version="1.0" encoding="utf-8" ?>
<FileTypes>
  <File type="photo">
    <Extension>.jpg</Extension>
    <Extension>.gif</Extension>
  </File>
  <File type="document">
    <Extension>.pdf</Extension>
  </File>
  <File type="video">
   <Extension>.flv</Extension>
  </File>
</FileTypes>

I would like to extract the extensions to a string array for a given file type. This is what I have so far:

var query = from m in _UploadFileTypes.Elements("FileTypes").Elements("File")
    where m.Attribute("type").Value.ToUpper() == fileTypeFilter
    select m.Elements("Extension");

foreach (var item in query)
{
    //item.ToString() does not yield the correct value...
}

Any help would be greatly appreciated!

+2  A: 

Try this:

var query = 
    from file in _UploadFileTypes.Root.Elements("File")
    let typeAttrib = file.Attribute("type")
    where 
        typeAttribute != null 
        && typeAttribute.Value.ToUpper() == fileTypeFilter
    from extension in file.Elements("Extension")
    select extension.Value;
foreach (var extension in query)
{
    // extension is the string content of the Extension element
}
Jacob
TrueWill
Good suggestion. I will update the code.
Jacob
That's only giving me the first element... for example, it's only returning .jpg in the photo type... it's not including both extensions.
Mike C.
Change Element("Extension") to Elements("Extension") to get all values.
Dennis Palmer
Oops, I missed that you could have multiple extensions. Time to modify it again.
Jacob
Perfect. I didn't realize you could use from clauses twice. I am a noobie at LinqToXML, but I am happy because I was somewhat close.
Mike C.
+1  A: 

@Jacob gave a great answer, but I believe simply using item.Value instead of item.ToString will give the value you're looking for using the code you had.

You can use IntelliSense to hover over your query to see that it's items are of type XElement. @Jacob's answer contains the .Value within the query, so in his version query contains strings.

Dennis Palmer
Thanks for the input. When I revert back to my original code item is a collection of XElements. It's almost like I need to have nested foreach loops. However, I know that there will only be one collection of elements with the specified attributes. It's almost like I need the original query to return a single collection of XElements so I can recurse through them instead of returning a collection of a collection.
Mike C.