1

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 查询返回联系人?

4

1 回答 1

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

这将返回代表所选公司联系人的匿名对象集合。每个对象都有城市、国家和名字的属性。

于 2013-06-14T21:04:59.647 回答