c# – Linq to XML Queries

前端之家收集整理的这篇文章主要介绍了c# – 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>有武器的名字.

猜你在找的C#相关文章