多XML追加操作

假设要统计当前系统中所有的试卷进行分析,试卷是以XML格式存储的,所有这就需要将所有零散的XML文件整合起来,处理成一个完整的XML文件,进行分析,

下面是简单额处理方法:

当前XML文件格式:

1 <?xml version="1.0" encoding="GB2312"?>
2 -<exam><examId>8ddf0e2e-ceba-4400-a20f-cf6f432bc5f5</examId>-<main>-<theme type="多选题" class="多选类">-<question type="多选题" class="多选类" pointType="0" point="2" difficulty="1" episteme="我新建的" questionSortId="bd01b0b4-d161-465d-9347-6e9af5ce639b" questionId="815539cc-3dbc-41a7-867c-153ca1f231b7"><questionsContent>我新建的</questionsContent><contentFile/><selectKey index="A">范德萨范德萨</selectKey><selectKey index="B">的萨芬的萨芬</selectKey><selectKey index="C">地方撒法士飞</selectKey><selectCount>3</selectCount><correctKey>1</correctKey><analyes>范德萨分</analyes><analyesFile/></question></theme></main><updata/></exam>
View Code

操作代码,一定要添加引用:using System.Xml.XPath;

 1     /// <summary>
 2         /// 获取文件夹中的所有XML,并且将所有XMl累加
 3         /// </summary>
 4         /// <returns></returns>
 5         public static XDocument GetXMLMore()
 6         {
 7             string examItemPath = @"C:UsersAdministratorDesktopXml";
 8             //试卷或者考试记录存放路径
 9             string path = "";
10             DirectoryInfo dir = new DirectoryInfo(examItemPath);
11             FileInfo[] dirinfo = dir.GetFiles();     //获取文件夹下面的子文件
12             //定义XML对象
13             XDocument dsExam = null;
14             //定义XML节点对象
15             XElement dsele = null;
16 
17             IEnumerable<XElement> list2 = null;
18             foreach (FileInfo info in dirinfo)    //遍历子文件
19             {
20                 //拼接循环文件路径
21                 path = examItemPath + "\" + info.Name.ToString();
22                 //如果当前XML对象为空的话,则说明当前文件是第一次加载,则直接添加到XML对象中去
23                 if (dsExam == null)
24                 {
25 
26                     try
27                     {
28                         dsExam = XDocument.Load(path);
29                     }
30                     catch (Exception)
31                     {
32 
33                         throw;
34                     }
35                 }
36                     //否则当前文件不是第一次加载,则说明XML对象中已经存在了XML数据,所有就不能直接读取,获取当前XML文件的节点,将改节点的文件追加到XML对象中去
37                 else
38                 {
39                     //读取XML文件
40                     dsele = XElement.Load(path);
41                     //查找节点
42                     list2 = dsele.XPathSelectElements("./main");
43                     //追加文件
44                     dsExam.Element("exam").Add(list2);
45                 }
46 
47             }
48             //返回文件
49             return dsExam;
50         }
View Code
原文地址:https://www.cnblogs.com/happygx/p/3248648.html