如何以XML格式序列化树分层数据

时间:2014-02-22 14:17:55

标签: c# xml xml-serialization

我在VS 2012中使用C#。我有一组Employee对象,如List<Employee> employees。每个Employee对象都具有EmployeeId,FirstName,LastName和ParentId的属性。树数据的深度是无限的。我想以XML格式序列化“employees”集合,如下所示:

<employees>
   <employee id="1">
     <firstName>aaa</firstName>
     <lastName>bbb</lastName>
     <parentId/>
        <children>
           <employee id="2">
               <firstName>ccc</firstName>
               <lastName>ddd</lastName>
               <parentId>1</parentId>
               <children>
                  <employee id="3">
                       <firstName>eee</firstName>
                       <lastName>fff</lastName>
                        <parentId>2</parentId>
                       <children/>
                    </employee>
                    <employee id="4">
                       <firstName>ggg</firstName>
                       <lastName>hhh</lastName>
                       <parentId>2</parentId>
                       <children/>
                    </employee>
               </children>
            </employee>
            <employee id="5">
                       <firstName>kkk</firstName>
                       <lastName>lll</lastName>
                       <parentId>1</parentId>
                       <children>
                            <employee id="6">
                                 <firstName>mmm</firstName>
                                 <lastName>nnn</lastName>
                                  <parentId>5</parentId>
                                  <children/>
                              </employee>
                       </children>
            </employee>
        </children>
   </employee>
</employees>  

List<Employee>employees集合的示例内容如下:

EmployeeId  FirstName   LastName    ParentId
1             aaa       bbb         null
2             ccc       ddd         1
5             kkk       lll         1
3             eee       fff         2
4             ggg       hhh         2
6             mmm       nnn         5

0 个答案:

没有答案