日期:2014-05-16  浏览次数:20379 次

C#操作XML的问题
产品(WEB)里面有个语言包,是XML文件,文件比较多,而且比较大,现在需要升级客户的程序,就需要将新的语言包中新增的key添加到客户环境的语言包中,不能直接替换,因为客户环境的语言包key相同的value可能不同(被修改为客户认同的文字)。
现在需要的功能就是添加新XML中在旧XML中没有的key。
我的做法是遍历旧XML文件,将所有的key和value填充到Hashtable,然后遍历新XML,如果Hashtable中不包含新XML中的key,就添加节点到旧XML中。经测试,2个2W行的XML执行需要耗时90秒的样子。请问有没有更加高效的方法?

        /// <summary>
        /// 更新XML文件
        /// </summary>
        /// <param name="itemNew">新XML文件</param>
        /// <param name="itemOld">旧XML文件(需要更新的文件)</param>
        private void UpdateXML(string itemNew, string itemOld)
        {
            XmlDocument xmlDocumentNew = new XmlDocument();
            xmlDocumentNew.Load(itemNew);
            XmlElement xmlElementNew = xmlDocumentNew.DocumentElement;

            XmlDocument xmlDocumentOld = new XmlDocument();
            xmlDocumentOld.Load(itemOld);
            XmlElement xmlElementOld = xmlDocumentOld.DocumentElement;

            if (xmlDocumentNew != null && xmlDocumentOld != null)
            {
                XmlNodeList xnListNew = xmlElementNew.ChildNodes;
                XmlNodeList xnListOld = xmlElementOld.ChildNodes;
                Hashtable hs = new Hashtable();
                foreach (XmlNode item in xnListOld)
                {
                    if (item.Attributes["Key"] != null)
                    {
                        if (!hs.Contains(item.Attributes["Key"].Value))
                        {
                            hs.Add(item.Attributes["Key"].Value, item.Attributes["Text"].Value);
                        }