Linq to XML Queries



假设我有一个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 上看到过这种类型的查询,但是我收藏夹中的链接现在指向错误的页面,我仍在尝试查找这些特定示例。任何帮助都非常感谢,

谢谢

试试这个:

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>

尝试使用此查询

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 中定义的类并反序列化它们。

试试这个

 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);
            }

不完全是。

您希望查找属性具有特定值的Customer然后选择第二个属性。

更像这样的东西:

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

相关内容

  • 没有找到相关文章

最新更新