XML文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCompany xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Company>
<CompanyID>Company A</CompanyID>
<CompanyName>Company A</CompanyName>
<CompanyRecID>1491</CompanyRecID>
<Contacts>
<Contact>
<City>Birmingham</City>
<Country>United States</Country>
<FirstName>Steven</FirstName>
</Contact>
<Contact>
<City>Birmingham</City>
<Country>United States</Country>
<FirstName>Natalie</FirstName>
</Contact>
</Contacts>
</Company>
<Company>
<CompanyID>Company B</CompanyID>
<CompanyName>Company B</CompanyName>
<CompanyRecID>1492</CompanyRecID>
<Contacts>
<Contact>
<City>Birmingham</City>
<Country/>
<FirstName>Greg</FirstName>
</Contact>
<Contact>
<City>Birmingham</City>
<Country/>
<FirstName>Robert</FirstName>
</Contact>
</Contacts>
</Company>
</ArrayOfCompany>
使用两行代码,我可以将该XML文件转换为数据集:
var dsCustomer = new System.Data.DataSet("CustomerDataSet");
dsCustomer.ReadXml(System.IO.Path.Combine(currentAssemblyDirectoryName, "company.xml"));
.NET了解架构。这是我使用ds.WriteXmlSchema命令时的样子:
给定公司名称,如何使用LINQ查询返回联系人?
答案 0 :(得分:2)
您可以使用LINQ to XML解析xml:
var name = "Company B";
var xdoc = XDocument.Load("company.xml");
var contacts = from company in xdoc.Descendants("Company")
where (string)company.Element("CompanyName") == name
from contact in company.Element("Contacts").Elements()
select new {
City = (string)contact.Element("City"),
Country = (string)contact.Element("Country"),
FirstName = (string)contact.Element("FirstName")
};
这将返回代表所选公司联系人的匿名对象集合。每个对象都有城市,国家和名字的属性。