2014-09-11 47 views
1

我完全沒有想法和我的C#/ LINQ/XML技能仍然非常薄弱。也許有人可以幫我一個相對簡單的任務,我不想寫周圍的整個PROGRAMM:c#xml顯示最高值

我需要得到客戶的最高-ID在這看起來有點像這樣的XML數據庫:

<xml> 
    <customers> 
    <customer> 
     <customerid>a00001</customerid> 
     <name>this</name> 
    </customer> 
    <customer> 
     <customerid>a00031</customerid> 
     <name>that</name> 
    </customer> 

等等...

我已經試過到目前爲止我已經用於其他LINQ/XML的是實際工作的代碼混合,用相結合的東西,我發現在這裏:

var readme = XElement.Load("someXML"); 
int tempHigh; 
var highIDs = 
    (from va in readme.Elements("customers").Elements("customer") 
    where Convert.ToInt32(va.Element("customerid").Value.Substring(2, 5)) > tempHigh 
    select Convert.ToInt32(va.Element("customerid").Value.Substring(2,5))); 

tempHigh = Convert.ToInt32(highIDs.Element("customerid").Value); 

return tempHigh; 

而有些東西不起作用。任何人都有一個想法,我沒有把數組中的所有數據,排序數組並給出了第一個元素(因爲那是我唯一留下的想法,但似乎有點太多)

+0

但爲什麼不使用LINQ並直接查詢XML?看到這個帖子http://stackoverflow.com/questions/12840647/get-max-attribute-value-from-xml-using-linq – Luca 2014-09-11 12:31:04

回答

5
int highestId = readme 
    .Elements("customers") 
    .Elements("customer") 
    .Select(cust => Convert.ToInt32(cust.Element("customerid").Value.Substring(1)) 
    .Max(); 
+1

在這種情況下.Substring(2)會更好,因爲customerid可能會獲得更多數字作爲客戶數量增長。 – fuchs777 2014-09-11 12:35:42

+0

@ fuchs777:這是一個很好的觀點。 – Bedford 2014-09-11 12:38:22

+2

爲什麼你從2開始不應該是1? – 2014-09-11 12:38:48

0

或更簡潔使用LINQ/xpath的組合

int id = readme.XPathSelectElements("/customers/customer/customerid").Max(cid => int.Parse(cid.Value.Substring(1)));