分组链接到XML多个层次结构

本文关键字:层次结构 XML 链接 | 更新日期: 2023-09-27 18:06:28

我在xml文件(student.xml)中有一个学生列表,如下:

           <root>
             <row>
               <school>AAAA </school>
               <grade> G1</grade>
               <student_name>xxx</student_name>
             </row>
             <row>
               <school>AAAA </school>
               <grade> G1</grade>
               <student_name>yyy</student_name>
             </row>
            <row>
               <school>AAAA </school>
               <grade> G2</grade>
               <student_name>zzz</student_name>
            </row>
            <row>
               <school>BBB</school>
               <grade> Gr1</grade>
               <student_name>sss</student_name>
            </row>
            <row>
               <school>BBB</school>
               <grade> Gr1</grade>
               <student_name>ttt</student_name>
            </row>
         </root>

我想用linq将同一学校同一年级的所有学生分组并保存在groupStudent.xml

预期结果(groupStudent.xml)

               <root>
                  <row>
                     <school>AAAA </school>
                     <grade> G1</grade>
                     <students>
                       <student_name>xxx</student_name>
                       <student_name>yyy</student_name>
                     </students>
                   </row>
                   <row>
                      <school>AAAA </school>
                      <grade> G2</grade>
                      <students>
                         <student_name>zzz</student_name>
                      </students>
                   </row>
                   <row>
                      <school>BBBB</school>
                      <grade> Gr1</grade>
                      <students>
                        <student_name>sss</student_name>
                        <student_name>ttt</student_name>
                     </students>
                </row>
              </root>   

分组链接到XML多个层次结构

您可以按照这种方式进行(其中PathOld是您现有xml的路径,PathNew是您想要保存新xml的路径)

        XDocument oldDoc = XDocument.Load(PathOld);
        var stGroup = oldDoc.Descendants("row").GroupBy(row =>
             new { s = row.Descendants("school").First().Value, g = row.Descendants("grade").First().Value },
             (key, gr) => new { key, list = gr}
             );

        XDocument newDoc = new XDocument();
        var root = new XElement("root");
        foreach (var item in stGroup)
        {
            var row = new XElement("row");
            row.Add(new XElement("school", item.key.s));
            row.Add(new XElement("grade", item.key.g));
            var stds = new XElement("students");
            foreach (var stud in item.list)
            {
                stds.Add(new XElement("student_name",
                    stud.Descendants("student_name").First().Value));
            }
            row.Add(stds);
            root.Add(row);
        }
        newDoc.Add(root);
        newDoc.Save(PathNew);