XML操作类

前端之家收集整理的这篇文章主要介绍了XML操作类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.C#操作XML的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

namespace GearProdLineMonitorSys
{
    class XMLOperation
    {
        private XmlDocument xmlDoc = null;
        private string xmlFileName;

        public XMLOperation(string strXmlFileName)
        {
            xmlFileName = strXmlFileName;   //record the current xml file name for saving

            xmlDoc = new XmlDocument();
            xmlDoc.Load(strXmlFileName);    //load the xml file to memory
        }

        public void XMLFileSave()
        {
            xmlDoc.Save(xmlFileName);       //保存到XML文档
        }

        #region XML文档节点读写

        public string GetXmlNodeValue(string strXPath,string strNodeName)
        {
            XmlNode xmlNode = GetXmlNodeByXpath(strXPath);

            if (xmlNode != null)
            {
                //遍历xpath节点下的所有子节点
                foreach (XmlNode node in xmlNode.ChildNodes)
                {
                    if (node.Name.ToLower() == strNodeName.ToLower())
                    {
                        //存在此节点则读取之
                        return node.InnerText;
                    }
                }
            }
            return string.Empty;
        }

        public string GetXmlNodeAttribute(string strXPath,string strAttrib)
        {
            XmlNode xmlNode = GetXmlNodeByXpath(strXPath);

            if (xmlNode != null)
            {
                foreach (XmlAttribute attrib in xmlNode.Attributes)
                {
                    if (attrib.Name.ToLower() == strAttrib.ToLower())
                    {
                        //存在此属性则读取之
                        return attrib.Value;
                    }
                }
            }
            return string.Empty;
        }

        public bool SetXmlNodeValue(string strXPath,string strNodeName,string strValue)
        {
            return CreateOrUpdateXmlNodeByXPath(strXPath,strNodeName,strValue,false);
        }

        public bool SetXmlNodeAttribute(string strXPath,string strAttribName,string strAttribValue)
        {
            return CreateOrUpdateXmlAttributeByXPath(strXPath,strAttribName,strAttribValue,false);
        }

        public bool AddXmlNode(string strXPath,true);
        }

        public bool AddXmlNodeWithAttribute(string strXPath,string strAttribValue)
        {
            return CreateXmlNodeByXPath(strXPath,string.Empty,strAttribValue);
        }

        public XmlNodeList GetXmlNodeList(string strXpath)
        {
            return GetXmlNodeListByXpath(strXpath);
        }

        public bool ClearXmlNode(string strXPath)
        {
            return ClearXmlNodeByPath(strXPath);
        }

        #endregion

        #region XML文档节点查询和读取

        /// <summary>
        /// 选择匹配XPath表达式的第一个节点XmlNode.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
        /// <returns>返回XmlNode</returns>
        private XmlNode GetXmlNodeByXpath(string xpath)
        {
            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                return xmlNode;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 选择匹配XPath表达式的节点列表XmlNodeList.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
        /// <returns>返回XmlNodeList</returns>
        private XmlNodeList GetXmlNodeListByXpath(string xpath)
        {
            try
            {
                XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);
                return xmlNodeList;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <returns>返回xmlAttributeName</returns>
        private XmlAttribute GetXmlAttribute(string xpath,string xmlAttributeName)
        {
            string content = string.Empty;
            XmlAttribute xmlAttribute = null;
            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    if (xmlNode.Attributes.Count > 0)
                    {
                        xmlAttribute = xmlNode.Attributes[xmlAttributeName];
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return xmlAttribute;
        }
        #endregion

        #region XML文档创建和节点或属性添加修改
        /// <summary>
        /// 创建一个XML文档
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="rootNodeName">XML文档根节点名称(须指定一个根节点名称)</param>
        /// <param name="version">XML文档版本号(必须为:"1.0")</param>
        /// <param name="encoding">XML文档编码方式</param>
        /// <param name="standalone">该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool CreateXmlDocument(string rootNodeName,string version,string encoding,string standalone)
        {
            bool isSuccess = false;
            try
            {
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version,encoding,standalone);
                XmlNode root = xmlDoc.CreateElement(rootNodeName);
                xmlDoc.AppendChild(xmlDeclaration);
                xmlDoc.AppendChild(root);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="value">属性值</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool CreateXmlNodeByXPath(string xpath,string xmlNodeName,string innerText,string xmlAttributeName,string value)
        {
            bool isSuccess = false;

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //存不存在此节点都创建
                    XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                    subElement.InnerXml = innerText;

                    //如果属性和值参数都不为空则在此新节点上新增属性
                    if (!string.IsNullOrEmpty(xmlAttributeName) && !string.IsNullOrEmpty(value))
                    {
                        XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                        xmlAttribute.Value = value;
                        subElement.Attributes.Append(xmlAttribute);
                    }

                    xmlNode.AppendChild(subElement);
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool CreateOrUpdateXmlNodeByXPath(string xpath,bool bCreate)
        {
            bool isSuccess = false;
            bool isExistsNode = false;//标识节点是否存在

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点下的所有子节点
                    foreach (XmlNode node in xmlNode.ChildNodes)
                    {
                        if (node.Name.ToLower() == xmlNodeName.ToLower())
                        {
                            //存在此节点则更新
                            node.InnerXml = innerText;
                            isExistsNode = true;
                            break;
                        }
                    }
                    if (!isExistsNode && bCreate)
                    {
                        //不存在此节点则创建
                        XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                        subElement.InnerXml = innerText;
                        xmlNode.AppendChild(subElement);
                    }
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="value">属性值</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool CreateOrUpdateXmlAttributeByXPath(string xpath,string value,bool bCreate)
        {
            bool isSuccess = false;
            bool isExistsAttribute = false;//标识属性是否存在

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    foreach (XmlAttribute attribute in xmlNode.Attributes)
                    {
                        if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                        {
                            //节点中存在此属性则更新
                            attribute.Value = value;
                            isExistsAttribute = true;
                            break;
                        }
                    }
                    if (!isExistsAttribute && bCreate)
                    {
                        //节点中不存在此属性则创建
                        XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                        xmlAttribute.Value = value;
                        xmlNode.Attributes.Append(xmlAttribute);
                    }
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }
        #endregion


        #region XML文档节点或属性删除
        /// <summary>
        /// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool DeleteXmlNodeByXPath(string xpath)
        {
            bool isSuccess = false;

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //删除节点
                    xmlNode.ParentNode.RemoveChild(xmlNode);
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 清除掉匹配XPath表达式下的所有节点(节点中的子元素同时被清除掉)
        /// </summary>
        /// <param name="xpath"></param>
        /// <returns></returns>
        private bool ClearXmlNodeByPath(string xpath)
        {
            bool isSuccess = false;

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //删除节点(无法使用RemoveAll,其会连同父节点属性一起删除掉)
                    while(xmlNode.ChildNodes.Count > 0)
                    {
                        XmlNode node = xmlNode.ChildNodes[0];
                        if (node != null)
                            xmlNode.RemoveChild(node);  //只能挨个删除节点
                    }
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;           
        }

        /// <summary>
        /// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要删除的xmlAttributeName的属性名称</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool DeleteXmlAttributeByXPath(string xpath,string xmlAttributeName)
        {
            bool isSuccess = false;
            bool isExistsAttribute = false;

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                XmlAttribute xmlAttribute = null;
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    foreach (XmlAttribute attribute in xmlNode.Attributes)
                    {
                        if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                        {
                            //节点中存在此属性
                            xmlAttribute = attribute;
                            isExistsAttribute = true;
                            break;
                        }
                    }
                    if (isExistsAttribute)
                    {
                        //删除节点中的属性
                        xmlNode.Attributes.Remove(xmlAttribute);
                    }
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 删除匹配XPath表达式的第一个节点中的所有属性
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <returns>成功返回true,失败返回false</returns>
        private bool DeleteAllXmlAttributeByXPath(string xpath)
        {
            bool isSuccess = false;

            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    xmlNode.Attributes.RemoveAll();
                }
                isSuccess = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return isSuccess;
        }
        #endregion

    }
}


2.调用

2.1 读取

static bool SystemConfig()
{
	//从配置文件(GearPLMonitor_Config.XML)读入连接字符串 
	try
	{
		 XMLOperation xmlOper = new XMLOperation(@"C:\WINDOWS\config.xml"); //read the XML file into memory

                string strparam = string.Empty;
  		if (string.Empty != (strparam = xmlOper.GetXmlNodeAttribute("system","type")))
                {
                    ///
                }
               if (string.Empty != (strparam = xmlOper.GetXmlNodeValue("system/dbparam","dbname")))
                {
                    DbOperation.strConnectSet.strDBName = strparam;
                }
                else
                {
                    return false;
                }

                if (string.Empty != (strparam = xmlOper.GetXmlNodeValue("system/dbparam","dbip")))
                {
                    DbOperation.strConnectSet.strDBIP = strparam;
                }
                else
                {
                    return false;
                }

                if (string.Empty != (strparam = xmlOper.GetXmlNodeValue("system/dbparam","portnum")))
                {
                    DbOperation.strConnectSet.strPortNum = strparam;
                }
                else
                {
                    return false;
                }

                if (string.Empty != (strparam = xmlOper.GetXmlNodeValue("system/dbparam","dbuser")))
                {
                    DbOperation.strConnectSet.strDBUser = strparam;
                }
                else
                {
                    return false;
                }

                if (string.Empty != (strparam = xmlOper.GetXmlNodeValue("system/dbparam","dbpassword")))
                {
                    DbOperation.strConnectSet.strDBPassword = strparam;
                }
                else
                {
                    return false;
                }
            }
     catch
     {
             return false;
     }

     return true;
}


2.2 写入

string monitortype = AutoMonitor ? "auto" : "unauto";
XMLOperation xmlOper = new XMLOperation(@"C:\WINDOWS\config.xml");  //read the XML file into memory
if (xmlOper.SetXmlNodeValue("system/monitortype","type",monitortype))
{
 xmlOper.XMLFileSave();
}
原文链接:https://www.f2er.com/xml/299740.html

猜你在找的XML相关文章