2011-05-16 97 views
6

遠的不說,我有一個看起來像這樣的XML文件:的LINQ to XML查詢

<?xml version="1.0" encoding="utf-8"?> 
<Customers> 
    <Customer Name="Jason Voorhees" WeaponPurchased="Machette" SalePrice="499.90" /> 
    <Customer Name="Michael Myers" WeaponPurchased="Kitchen Knife" SalePrice="96.75" /> 
</Customers> 

是否有可能,使用LINQ,做這樣的事情:?

foreach customer in Customers select WeaponPurchased where Name equals "Jason Voorhees" 

或:

foreach customer in Customers select customer 
label1.Text += "Name: " + customer.Name + Environment.NewLine + "WeaponPurchased: " + customer.WeaponPurchased; 

我以前見過這種類型的查詢MSDN上,但在我的收藏夾中的鏈接導致錯誤的頁面,現在,我仍然試圖找到這些特定的例子。任何幫助是非常讚賞,

謝謝

回答

5

試試這個:

var doc = XDocument.Load(Path.Combine(path, "file.xml")); 
var query = from c in doc.Descendants("Customer") 
      where c.Attributes("Name").Single().Value == "Jason Voorhees" 
      select c.Attributes("WeaponPurchased").Single().Value; 

它將返回IEnumerable<string>的武器名稱。

+0

感謝您的幫助@Ladislav! :) :) :) – 2011-05-16 10:11:53

3

嘗試使用此查詢

XElement root = XDocument.Load(path).Root; 
var result = root.Elements("Customers"). 
      Where(x => x.Attribute("Name").Value =="Jason Voorhees"). 
      Select(x => x.Attribute("WeaponPurchased").Value)); 

或者你可以嘗試創建其中在XML定義的類和反序列化它們。

1

試試這個

public class Customer 
    { 
     public string Name { get; set; } 
     public string WeaponPurchased { get; set; } 
     public string SalePrice { get; set; } 
    } 

和查詢XML像下面

var customer = from c in XDocument.Load("XMLPATH").Descendants("Customer") 
          where (string)c.Attribute("Name")=="Jason Voorhees" 
          select new Customer 
          { 
           Name=(string)c.Attribute("Name"), 
           WeaponPurchased = (string)c.Attribute("WeaponPurchased"), 
           SalePrice = (string)c.Attribute("SalePrice"), 

          }; 

      foreach (var item in customer) 
      { 
       Console.WriteLine(item.WeaponPurchased); 

      } 
0

不太。

你想找到一個Customer其中屬性具有一定的價值,然後選擇第二屬性。

更多的東西是這樣的:

from customer in Customers 
where customer.Attribute("Name").Value equals "Jason Voorhees" 
select customer.Attribute("WeaponPurchased").Value