2013-04-25 144 views
0

我想基於錯誤代碼ret.Revrevie錯誤消息,我怎樣才能使用LINQ?讀取基於另一個屬性的XML屬性值

這裏是我的xml文檔佈局

<?xml version="1.0" encoding="utf-8" ?> 
<errors> 
    <error code="101" message="Our Database is currently experience problems!"> 
    </error> 
</errors> 

這裏是C#

XmlDocument doc = new XmlDocument(); 
doc.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml")); 

回答

0

那麼我的加載代碼,你可以一次加載該文件,把它變成一個Dictionary<int, string>這樣的:

var doc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml")); 
var errors = doc.Root.Elements("error") 
       .ToDictionary(x => (int) x.Attribute("code"), 
           x => (string) x.Attribute("message")); 

(您可以在web應用程序加載中執行此操作。)

或者,如果你真的只需要找到一條消息:

var doc = XDocument.Load(HttpContext.Current.Server.MapPath("/App_Data/ErrorCodes.xml")); 
var errors = doc.Root.Elements("error") 
       .Where(x => (int) x.Attribute("code") == code) 
       .Single() 
       .Attribute("message").Value; 

注意XDocument是LINQ到XML的一部分; XmlDocument不是。