XML to Dataset:如何访问节点中的复杂类型?

时间:2013-06-14 21:01:29

标签: c# .net xml linq

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命令时的样子: enter image description here

给定公司名称,如何使用LINQ查询返回联系人?

1 个答案:

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

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