Mike Cole
Mike Cole

Reputation: 14713

LinqtoXML: Getting element values

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!

Upvotes: 1

Views: 166

Answers (2)

Jacob
Jacob

Reputation: 78848

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
}

Upvotes: 2

CoderDennis
CoderDennis

Reputation: 13837

@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.

Upvotes: 1

Related Questions