2011-05-16 92 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