将Xml读取到DataTable

时间:2014-05-23 11:38:14

标签: c# xml linq

将以下xml文件读取到DataTable的有效方法是什么?我无法做到 获取重复的项目数据。

<Employees>

<Employee>
    <EmployeeID>25</EmployeeID>
    <Project>
        <ProjectId>1001</ProjectId>
        <STARTDT>2008-08-18</STARTDT>
    </Project>
</Employee>

<Employee>
    <EmployeeID>26</EmployeeID>
    <Project>
        <ProjectId>1002</ProjectId>
        <STARTDT>2009-11-09</STARTDT>
        <ENDDT>2013-11-04</ENDDT>
    </Project>
    <Project>
        <ProjectId>1003</ProjectId>
        <STARTDT>2013-11-05</STARTDT>
    </Project>
</Employee>

</Employees>

预期结果

--------------------------------------------------------------------
EmployeeId    ProjectId     StartDt          EndDt
-------------------------------------------------------------------
25             1001        2008-08-18
26             1002        2009-11-09
26             1003        2013-11-05

1 个答案:

答案 0 :(得分:2)

将其读入DataSet

String xml = "<Employees><Employee><EmployeeID>1328911000001108</EmployeeID><Project><ProjectId>5000456001090</ProjectId><STARTDT>2008-08-18</STARTDT></Project></Employee><Employee><EmployeeID>1330611000001103</EmployeeID><Project><ProjectId>5017007023913</ProjectId><STARTDT>2009-11-09</STARTDT><ENDDT>2013-11-04</ENDDT></Project><Project><ProjectId>5017007019213</ProjectId><STARTDT>2013-11-05</STARTDT></Project></Employee></Employees>";
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(xml), XmlReadMode.InferSchema);

这里的关键是XmlReadMode.InferSchema,它将在DataSet中生成两个表,由EmployeeID链接。