首页 新闻 会员 周边

C#操作XML问题

0
悬赏园豆:50 [已解决问题] 解决于 2014-03-19 16:54

产品(WEB)里面有个语言包,是XML文件,文件比较多,而且比较大,现在需要升级客户的程序,就需要将新的语言包中新增的key添加到客户环境的语言包中,不能直接替换,因为客户环境的语言包key相同的value可能不同(被修改为客户认同的文字)。

现在需要的功能就是添加新XML中在旧XML中没有的key。

我的做法是遍历旧XML文件,将所有的key和value填充到Hashtable,然后遍历新XML,如果Hashtable中不包含新XML中的key,就添加节点到旧XML中。经测试,2个2W行的XML执行需要耗时90秒的样子。请问有没有更加高效的方法?

 1 /// <summary>
 2         /// 更新XML文件
 3         /// </summary>
 4         /// <param name="itemNew">新XML文件</param>
 5         /// <param name="itemOld">旧XML文件(需要更新的文件)</param>
 6         private void UpdateXML(string itemNew, string itemOld)
 7         {
 8             XmlDocument xmlDocumentNew = new XmlDocument();
 9             xmlDocumentNew.Load(itemNew);
10             XmlElement xmlElementNew = xmlDocumentNew.DocumentElement;
11 
12             XmlDocument xmlDocumentOld = new XmlDocument();
13             xmlDocumentOld.Load(itemOld);
14             XmlElement xmlElementOld = xmlDocumentOld.DocumentElement;
15 
16             if (xmlDocumentNew != null && xmlDocumentOld != null)
17             {
18                 XmlNodeList xnListNew = xmlElementNew.ChildNodes;
19                 XmlNodeList xnListOld = xmlElementOld.ChildNodes;
20                 Hashtable hs = new Hashtable();
21                 foreach (XmlNode item in xnListOld)
22                 {
23                     if (item.Attributes["Key"] != null)
24                     {
25                         if (!hs.Contains(item.Attributes["Key"].Value))
26                         {
27                             hs.Add(item.Attributes["Key"].Value, item.Attributes["Text"].Value);
28                         }
29                     }
30                 }
31                 int count = 0;
32                 for (int i = 0; i < xnListNew.Count; i++)
33                 {
34                     if (xnListNew[i].Attributes["Key"] != null)
35                     {
36                         if (!hs.Contains(xnListNew[i].Attributes["Key"].Value))
37                         {
38                             xmlElementOld.AppendChild(xmlDocumentOld.ImportNode(xnListNew[i], true));
39                             count++;
40                         }
41                     }
42                 }
43                 if (count > 0)
44                 {
45                     list_Message.Items.Add(string.Format("文件:{0} 成功添加{1}条数据。", itemOld, count));
46                 }
47             }
48             xmlDocumentOld.Save(itemOld.ToString());
49         }
View Code

 

缒絿的主页 缒絿 | 初学一级 | 园豆:157
提问于:2014-03-18 13:49
< >
分享
最佳答案
0

旧文件有20000条记录,新文件有20002条记录,那么要执行最多400040000次比较,你说它能不慢么?换个比较算法吧。

收获园豆:20
飞扬的尘埃 | 小虾三级 |园豆:1318 | 2014-03-18 18:20

求算法!谢谢。

缒絿 | 园豆:157 (初学一级) | 2014-03-18 19:38
其他回答(1)
0

你有没有测试后发现实际上慢在你读取 XML 的方式上?

你应该使用 XmlReader 来读取,然后用 XmlWritter 来写。

收获园豆:30
Launcher | 园豆:45045 (高人七级) | 2014-03-18 15:22

写数据并不慢,主要慢在遍历,以及在HashTable中查找是否有相同的键!

支持(0) 反对(0) 缒絿 | 园豆:157 (初学一级) | 2014-03-18 15:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册