2014-09-01 63 views
1

我想,當你通過UID搜索從以下XML只返回一個結果:我使用這下面的代碼如何使用LINQ從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元素,而不僅僅是文件名:

enter image description here

有anyw唉剛剛做了相當於'在LINQ中'從選擇文件,這將允許我只返回該文件的'文件'值?我已經試過,沒有運氣這樣做:

var fileName = fileList[0]['File']; 

非常感謝

+3

加上'。選擇(X =>(串)x.Element( 「文件」))''後Where' – 2014-09-01 15:33:51

+0

謝謝你這麼多LB!請添加爲答案,我會接受:) – Nick 2014-09-01 15:34:48

回答

4

只需添加

.Select(x=>(string)x.Element("File")) 

Where

PS:因爲它止跌鑄造的XElement的類型是安全的即使File標籤不存在也不會拋出異常(只返回null)

+1

完美的作品,非常感謝你! – Nick 2014-09-01 15:36:31

+0

+1 - 不知道關於鑄件的珍聞。 – 2014-09-01 15:40:09

2

Select()File節點的Value財產在你的LINQ:

var fileList = xml.Descendants("Photo") 
     .Where(e => e.Attribute("UID") != null && (string)e.Attribute("UID").Value == ID) 
     .Select(n => n.Element("File").Value) 
     .ToList(); 
+0

非常感謝Cory,這個作品很棒:) – Nick 2014-09-01 15:36:47

+2

這會返回包含xml標籤的元素而不是值。 – 2014-09-01 15:37:31

+1

@ Selman22:已修復。 – 2014-09-01 15:39:01