XML操作相关工具

using System;
using System.Collections;
using System.Text;
using System.Xml;
using System.IO;

namespace BrainSoft.Common
{
 /// <summary>
 /// 描    述:XML操作相关工具
 /// 参数说明:
 /// 说    明:
 /// 创 建 人:thanktheworld

 /// 日    期:now
 /// 历史修改记录:
 /// </summary>
 public class XMLUtil
 {
  /// <summary>
  /// 使用XPath定位xml中结点的值

  /// </summary>
  /// <param name="xmlDocument">XML文件</param>
  /// <param name="XPath">要取的xml路径</param>
  /// <returns></returns>
  public static string GetValueFromXmlByXPath(XmlDocument xmlDocument, string XPath)
           
   XmlNodeList xmlNodeList = SelectNodes(xmlDocument,XPath);
   if (xmlNodeList.Count > 0)
    if (XPath.IndexOf("@") >= 0)
     return xmlNodeList[0].Value;
    else
     return xmlNodeList[0].InnerText;
   else
    return null;
                
  /// <summary>
  /// 选择匹配 XPath 表达式的节点列表。

  /// </summary>
  /// <param name="xmlDocument">XML文件</param>
  /// <param name="XPath">要取的xml路径</param>
  /// <returns></returns>
  public static XmlNodeList SelectNodes(XmlDocument xmlDocument, string XPath)
  {
   XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDocument.NameTable);
   xnm.AddNamespace("pf", xmlDocument.DocumentElement.NamespaceURI);

   #region strXPath中的“/”替换成“/pf:”,"/@"除外
   //特殊字符串,以来替换"/@",最后,再替换回来。

   string strSpecial = @"!@#$%^&*(!@#$%^&*())!@#$%^&*(!@#$%^&*())";

   string temp1 = XPath.Replace(@"/@", strSpecial);
   string temp2 = temp1.Replace(@"/", @"/pf:");
   string newXPath = temp2.Replace(strSpecial, @"/@");
   #endregion

   XmlNodeList xmlNodeList = xmlDocument.SelectNodes(newXPath, xnm);
   return xmlNodeList;
  }
  /// <summary>
  /// 根据xpath来获取属性值

  /// </summary>
  /// <param name="xmlNode">结点</param>
  /// <param name="attributeName">属性名</param>
  /// <param name="XPath">要取的xml路径</param>
  /// <param name="throwException">发生错误是否抛异常</param>
  /// <returns></returns>
  public static string GetXmlNodeAttribute(XmlNode xmlNode, string attributeName, string XPath, bool throwException)
  {
   if (xmlNode.Attributes[attributeName] == null)
   {
    if (throwException)
    {
     throw(new System.Exception(string.Format("{0}/@{1}", XPath, attributeName)));                 
    }
    return null;
   }
   else
   {
    return xmlNode.Attributes[attributeName].Value;
   }
  }

  /// <summary>
  /// 根据XPath来获取属性值

  /// </summary>
  /// <param name="xmlNode">结点</param>
  /// <param name="attributeName">属性名</param>
  /// <param name="XPath">要取的xml路径</param>
  /// <returns></returns>
  public static string GetXmlNodeAttribute(XmlNode xmlNode, string attributeName, string XPath)
  {
   return GetXmlNodeAttribute(xmlNode, attributeName, XPath,true);
  }

  /// <summary>
  /// 根据FileName来获取属性值
  /// </summary>
  /// <param name="FileName">文件路径</param>
  /// <param name="XPath">要取的xml路径</param>
  /// <param name="Node">结点</param>
  /// <param name="Attribute">属性名</param>
  /// <returns></returns>
  public static string GetXMLcfgValue(string FileName,string xPath,string Node ,string Attribute)
  {
   try
   {
    XmlDocument doc = new XmlDocument();
    doc.Load(FileName);
    XmlNode node = doc.SelectSingleNode (xPath + "/" + Node);
    if (node!=null)
    {
     if (node.Attributes.GetNamedItem(Attribute)!=null)
     {
      return node.Attributes[Attribute].Value ;
     }
    }
    return "";
   }
   catch(Exception)
   {
    return "";
   }

  }

  /// <summary>
  /// 描    述:读取XML配置文件数据;
  /// </summary>
  /// <param name="keyname">xml文件的位置</param>
  /// <param name="keynode">结点</param>
  /// <param name="xmlFilePath">属性名</param>
  /// <returns></returns>
  public static string GetXmlConfigValue(string xmlFilePath, string keynode, string keyname)
  {
   try
   {
    if (File.Exists(xmlFilePath) == true)
    {
     XmlDocument doc = new XmlDocument();
     doc.Load(xmlFilePath);
     XmlNodeList nodes = doc.SelectNodes(keynode);
     foreach (XmlNode node in nodes)
     {
      if (node.Attributes["key"].Value == keyname)
      {
       return node.Attributes["value"].Value.ToString();
      }
     }
     doc = null;
     //doc.Save(xmlFilePath);
    }
    return "";
   }
   catch
   {
    return "";
   }
  }
  /// <summary>
  /// 描    述:向XML配置文件写数据;
  /// </summary>
  public static bool SetXmlConfigValue(string xmlFilePath, string keynode, string keyname, string keyvalue)
  {
   try
   {
    string[] _NodeNames = keynode.ToString().Split(char.Parse("/"));
    XmlDocument xmlDoc = new XmlDocument();
    XmlNode xmlNode = null;
    XmlElement xmlelem = null;
    XmlAttribute attNode = null;
    if (File.Exists(xmlFilePath) == false)
    {
     xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
     xmlDoc.AppendChild(xmlNode);

     //加入一个根元素
     xmlelem = xmlDoc.createElement_x("", _NodeNames[1], "");
     xmlNode = xmlDoc.AppendChild(xmlelem);
    }
    else
    {
     xmlDoc.Load(xmlFilePath);
     xmlNode = xmlDoc.SelectSingleNode(_NodeNames[1]);
    }

    for (int i = 2; i < _NodeNames.Length; i++)
    {
     if (xmlNode.SelectSingleNode(_NodeNames[i]) == null)
     {
      xmlelem = xmlDoc.createElement_x(_NodeNames[i]);
      xmlNode = xmlNode.AppendChild(xmlelem);
     }
     else
     {
      xmlNode = xmlNode.SelectSingleNode(_NodeNames[i]);
     }
    }

    bool _IsAddNode = true;
    XmlNodeList xmlNodes = xmlDoc.SelectNodes(keynode);
    foreach (XmlNode node in xmlNodes)
    {
     if (node.Attributes.Count > 0)
     {
      if (node.Attributes["key"].Value == keyname)
      {
       node.Attributes["value"].Value = keyvalue;
       _IsAddNode = false;
      }
     }
    }
    if (_IsAddNode == true)
    {
     foreach (XmlNode node in xmlNodes)
     {
      if (node.Attributes.Count==0)
      {
       attNode = xmlDoc.CreateAttribute("key");
       attNode.Value = keyname;
       node.Attributes.Append(attNode);

       attNode = xmlDoc.CreateAttribute("value");
       attNode.Value = keyvalue;
       node.Attributes.Append(attNode);
       _IsAddNode = false;
      }
     }
    }
    if (_IsAddNode == true)
    {
     xmlNode = xmlNode.ParentNode;
     xmlelem = xmlDoc.createElement_x(_NodeNames[_NodeNames.Length - 1]);
     xmlNode = xmlNode.AppendChild(xmlelem);

     attNode = xmlDoc.CreateAttribute("key");
     attNode.Value = keyname;
     xmlNode.Attributes.Append(attNode);

     attNode = xmlDoc.CreateAttribute("value");
     attNode.Value = keyvalue;
     xmlNode.Attributes.Append(attNode);
    }
    xmlDoc.Save(xmlFilePath);
    return true;
   }
   catch
   {
    return false;
   }
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值