批量更新带有命名空间的XML文件的多个节点值

        /// <summary>
        /// 批量修改节点值
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <param name="parameters">节点,值</param>
        /// <param name="nameSpace">命名空间</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.BatchUpdateNodeValue(path, parameters, nameSpace)
      * 旺财软件 WangCaiSoft ************************************************/ public static void BatchUpdateNodeValue(string filePath, List<KeyValuePair<string, string>> parameters, string nameSpace = "") { if (!string.IsNullOrEmpty(filePath)) { if (!filePath.Contains(@":\") && filePath.Contains(@"/")) { filePath = System.Web.HttpContext.Current.Server.MapPath(filePath); } try { var doc = new XmlDocument(); doc.Load(filePath); if (parameters != null && parameters.Count > 0) { foreach (var parameter in parameters) { if (parameter.Key != null && parameter.Value != null) { var node = parameter.Key; var value = parameter.Value; var xn = doc.SelectSingleNode(node); if (!string.IsNullOrEmpty(nameSpace)) { XmlNamespaceManager xmlnam = new XmlNamespaceManager(doc.NameTable); xmlnam.AddNamespace("a", nameSpace); node = node.Replace("/", "/a:"); xn = doc.SelectSingleNode(node, xmlnam); } var xe = (XmlElement)xn; if (xe != null) { xe.InnerText = value; } } } } //最后一次性保存 doc.Save(filePath); } catch (Exception ex) { LogUtil.WriteException(ex); } } }

调用方法

                    var parameters = new List<KeyValuePair<string, string>>();
                    parameters.Add(new KeyValuePair<string, string>("/DocumentID/ID", orderNumber));
                    parameters.Add(new KeyValuePair<string, string>("/Status/Code", "Processed"));
                    parameters.Add(new KeyValuePair<string, string>("/CreditCardAuthCode", transactionKey));
                    parameters.Add(new KeyValuePair<string, string>("/AuthorizedBy", userName));
                    parameters.Add(new KeyValuePair<string, string>("/AuthorizedDate", transactionDate));
                    
                    XmlHelper.BatchUpdateNodeValue(filePath, parameters, "http://schema.infor.com/InforOAGIS/2");

  

posted @ 2017-07-20 16:21  troy.cui  阅读(381)  评论(0编辑  收藏  举报