将XML文档转换为类

时间:2015-02-19 20:54:58

标签: c# xml

我有以下来自3方并保存在数据库中的xml文档。我试图找出获取文档和加载类的最佳方法,这样我就可以操作数据,然后将它保存到代表该类的表中的数据库中。

<Payroll xmlns:dtv="http://www.datavantagecorp.com/xstore/"><dtv:Payroll>
<dtv:StartDate>2015-02-08</dtv:StartDate>
<dtv:EndDate>2015-02-14</dtv:EndDate>
<dtv:PostedDate>2015-02-16</dtv:PostedDate>
<dtv:Employee EmployeeId="111122">
<dtv:EmployeePayStatus></dtv:EmployeePayStatus>
<dtv:PayrollStoreNumber>8009</dtv:PayrollStoreNumber>
<dtv:ReviewedDate></dtv:ReviewedDate>
<dtv:PayrollCategory Category="OT">
<dtv:PayrollDate>2015-02-14</dtv:PayrollDate>
<dtv:Hours>0.53</dtv:Hours>
<dtv:PayrollDate>2015-02-12</dtv:PayrollDate>
<dtv:Hours>0.77</dtv:Hours>
<dtv:PayrollDate>2015-02-11</dtv:PayrollDate>
<dtv:Hours>0.13</dtv:Hours>
<dtv:PayrollDate>2015-02-09</dtv:PayrollDate>
<dtv:Hours>0.12</dtv:Hours>
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="DT">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="REGULAR">
<dtv:PayrollDate>2015-02-09</dtv:PayrollDate>
<dtv:Hours>8.00</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>8.12</dtv:TotalHours>
</dtv:WorkCode>
<dtv:PayrollDate>2015-02-10</dtv:PayrollDate>
<dtv:Hours>6.03</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>6.03</dtv:TotalHours>
</dtv:WorkCode>
<dtv:PayrollDate>2015-02-11</dtv:PayrollDate>
<dtv:Hours>8.00</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>8.13</dtv:TotalHours>
</dtv:WorkCode>
<dtv:PayrollDate>2015-02-12</dtv:PayrollDate>
<dtv:Hours>8.00</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>8.77</dtv:TotalHours>
</dtv:WorkCode>
<dtv:PayrollDate>2015-02-13</dtv:PayrollDate>
<dtv:Hours>6.81</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>6.81</dtv:TotalHours>
</dtv:WorkCode>
<dtv:PayrollDate>2015-02-14</dtv:PayrollDate>
<dtv:Hours>3.16</dtv:Hours>
<dtv:WorkCode code="888">
<dtv:TotalHours>3.69</dtv:TotalHours>
</dtv:WorkCode>
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="SICK">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="VACATION">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="HOLIDAY">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="RT">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="EO">
</dtv:PayrollCategory>
<dtv:PayrollCategory Category="RSA">
</dtv:PayrollCategory>
</dtv:Employee>
</dtv:Payroll>
</Payroll>

XML可以在工资单中包含多个员工。我以为我会有以下课程:

工资单 雇员 PayrollCategory

每个Payroll的位置都有一个员工列表,每个员工都有一个PayrollCategory列表。我已开始沿着以下路径前进,但不确定这是否是最佳方式,或者是否有更好的解决方案。

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(row[0].ToString());
                }

如何处理此问题的任何建议或链接将不胜感激。

2 个答案:

答案 0 :(得分:0)

我建议您为XML元素创建类,您可以从XML文档中序列化/反序列化。关于如何做到这一点(例如找到的here),有一些问题和答案。

如果您的XML文档有XSD架构,您甚至可以自动生成类。

答案 1 :(得分:-2)

foreach (var row in ds.Tables[0].Rows)
{
    var doc = XDocument.Load(new MemoryStream(new UTF8Encoding().GetBytes(row[0])));
}