开发者

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</E开发者_JS百科xtension>
  </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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜