当您通过UID搜索时,我正在尝试从以下XML返回单个结果:
<Photos>
<Photo UID="a3d508784ff3456da7bf2ff8ce08e577">
<Date>2014-08-22T14:00:32.7958436+01:00</Date>
<File>a3d508784ff3456da7bf2ff8ce08e577.jpg</File>
<CrimeRef>CR123456/14</CrimeRef>
</Photo>
<Photo UID="735620a99f2c4dfd9f2c1870136e993e">
<Date>2014-08-22T14:07:29.0364635+01:00</Date>
<File>735620a99f2c4dfd9f2c1870136e993e.jpg</File>
<CrimeRef>CR999999/99</CrimeRef>
</Photo>
<Photo UID="c186993e8a0246c29dd180396dfea47b">
<Date>2014-08-22T14:07:29.6835282+01:00</Date>
<File>c186993e8a0246c29dd180396dfea47b.jpg</File>
<CrimeRef>CR999999/99</CrimeRef>
</Photo>
</Photos>
我正在使用以下代码:
var fileList = xml.Descendants("Photo")
.Where(e => e.Attribute("UID") != null
&& (string)e.Attribute("UID").Value == ID)
.ToList();
var fileName = fileList[0];
问题是fileList [0]具有整个XML元素,而不仅仅是文件名:
有没有在LINQ中执行等效的'从'中选择文件,这样我才能返回该元素的'File'值?我尝试过这样做没有运气:
var fileName = fileList[0]['File'];
非常感谢
答案 0 :(得分:4)
添加
.Select(x=>(string)x.Element("File"))
在Where
之后
PS:将XElement转换为类型更安全,因为即使File标记不存在也不会抛出异常(只返回null)
答案 1 :(得分:2)
Select()
File
节点的Value
属性:
var fileList = xml.Descendants("Photo")
.Where(e => e.Attribute("UID") != null && (string)e.Attribute("UID").Value == ID)
.Select(n => n.Element("File").Value)
.ToList();