using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.IO;

namespace XML.Helper
{
    public class xmlHelper
    {
        #region 字段
        /// <summary>
        /// xml文件物理路径
        /// </summary>
        private  string _FilePath = string.Empty;
        /// <summary>
        /// xml文档
        /// </summary>
        private XmlDocument _xml;
        /// <summary>
        /// xml文档根节点
        /// </summary>
        private XmlElement _element;
        #endregion

public xmlHelper()
        {
            //
        }

/// <summary>
        /// 给xml文档路径赋值
        /// </summary>
        /// <param name="xmlFilePath"></param>
        public xmlHelper(string xmlFilePath)
        {
            _FilePath = xmlFilePath;
        }

/// <summary>
        /// 获取指定路径节点
        /// </summary>
        /// <param name="xPath"></param>
        /// <returns></returns>
        public static XmlNode GetXmlNode(string xmlFileName, string xPath)
        {
            XmlDocument xmldocument = new XmlDocument();
            //加载xml文档
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                return xmlnode;
            }
            catch
            {
                return null;
            }
        }

/// <summary>
        /// 获取指定路径节点下孩子节点列表
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <returns></returns>
        public static XmlNodeList GetXmlNodeList(string xmlFileName, string xPath)
        {
            XmlDocument xmldocument = new XmlDocument();
            //加载xml文档
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNodeList xmlnodelist = xmldocument.SelectNodes(xPath);
                return xmlnodelist;
            }
            catch
            {
                return null;
            }
        }

/// <summary>
        /// 获取指定路径节点的属性与指定属性名匹配
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="attributeName">指定的属性名称</param>
        /// <returns></returns>
        public static XmlAttribute GetXmlAttribute(string xmlFileName, string xPath,string attributeName)
        {
            XmlAttribute xmlattribute=null;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.Attributes.Count > 0)
                    {
                        xmlattribute = xmlnode.Attributes[attributeName];
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return xmlattribute;
        }

/// <summary>
        /// 获取指定节点的属性集合
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <returns></returns>
        public static XmlAttributeCollection GetNodeAttributes(string xmlFileName, string xPath)
        {
            XmlAttributeCollection xmlattributes = null;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.Attributes.Count > 0)
                    {
                        xmlattributes = xmlnode.Attributes;
                       
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return xmlattributes;
        }

/// <summary>
        /// 更新指定节点的某一属性设定其属性值value
        /// </summary>
        /// <param name="xmlFileName">xml文档路径</param>
        /// <param name="xPath"></param>
        /// <param name="attributeOldeName">旧属性名称</param>
        /// <param name="attributeNewName">新属性名称</param>
        /// <param name="value">属性值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool UpdateAttribute(string xmlFileName, string xPath, string attributeName, string value)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    foreach (XmlAttribute attribute in xmlnode.Attributes)
                    {
                        if (attribute.Name.ToString().ToLower() == attributeName.ToLower())
                        {
                            isSuccess = true;
                            attribute.Value = value;
                            xmldocument.Save(xmlFileName);
                            break;
                        }
                    }
                }
            }
            catch(Exception err)
            {
                throw err;
            }
            return isSuccess;
        }

/// <summary>
        /// 删除指定节点的所有属性
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool DeleteAttributes(string xmlFileName, string xPath)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.Attributes.Count > 0)
                    {
                        xmlnode.Attributes.RemoveAll();
                        xmldocument.Save(xmlFileName);
                        isSuccess = true;
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return isSuccess;
        }

/// <summary>
        /// 删除匹配属性名称的指定节点的属性
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <param name="attributeName"></param>
        /// <returns></returns>
        public static bool DeleteOneAttribute(string xmlFileName, string xPath, string attributeName)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            XmlAttribute xmlAttribute = null;
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.Attributes.Count > 0)
                    {
                        foreach (XmlAttribute attribute in xmlnode.Attributes)
                        {
                            if (attribute.Name.ToLower() == attributeName.ToLower())
                            {
                                xmlAttribute = attribute;
                                break;
                            }
                        }
                    }
                    if (xmlAttribute != null)
                    {
                        xmlnode.Attributes.Remove(xmlAttribute);
                        xmldocument.Save(xmlFileName);
                        isSuccess = true;
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return isSuccess;
        }

/// <summary>
        /// 创建指定节点的属性,如果属性存在则不创建
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <param name="attributeName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool AddAttribute(string xmlFileName, string xPath,string attributeName,string value)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.Attributes.Count > 0)//遍历判断有无此属性
                    {
                        foreach (XmlAttribute attribute in xmlnode.Attributes)
                        {
                            if (attribute.Name.ToLower() == attributeName.ToLower())
                            {
                                //有则不改,直接返回true;
                                return true;
                            }
                        } 
                    }
                    XmlAttribute xmlAttribute = xmldocument.CreateAttribute(attributeName);
                    xmlAttribute.Value = value;
                    xmlnode.Attributes.Append(xmlAttribute);
                    xmldocument.Save(xmlFileName);
                    isSuccess = true;
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return isSuccess;
        }

/// <summary>
        /// 为某一指定路径节点下添加新的节点,如果该节点存在,则不添加
        /// </summary>
        /// <param name="xmlFileName">xml文档路径</param>
        /// <param name="xPath">需要添加节点的路径</param>
        /// <param name="nodeName">节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <returns>成功返回true,存在返回false</returns>
        public static bool AddNode(string xmlFileName, string xPath, string nodeName, string innerText)
        {
            bool isSuccess = false;
            bool isExisitNode = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    isExisitNode = true;
                }
                if (!isExisitNode)
                {
                    XmlElement subElement = xmldocument.CreateElement(nodeName);
                    subElement.InnerText = innerText;
                    xmlnode.AppendChild(subElement);
                    isSuccess = true;
                    xmldocument.Save(xmlFileName);
                }
            }
            catch (Exception err)
            {
                throw err;
            }
           
            return isSuccess;
        }

/// <summary>
        /// 查找指定的节点,更新其节点值
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <param name="nodeName"></param>
        /// <param name="innerText"></param>
        /// <returns></returns>
        public static bool UpdateNode(string xmlFileName, string xPath, string nodeName, string innerText)
        {
            bool isSuccess = false;
            bool isExisitNode = false;
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.LoadXml(xmlFileName);
            XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
            try
            {
                if (xmlnode != null)
                {
                    isExisitNode = true;
                }
                if (!isExisitNode)
                {
                    xmlnode.InnerText = innerText;
                    isSuccess = true;
                    xmldocument.Save(xmlFileName);
                }
            }
            catch (Exception err)
            {
                throw err;
            }

return isSuccess;
        }

/// <summary>
        /// 删除指定节点名称为nodeName的所有节点,如果该节点有子节点,则不能删除
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        public static bool deleteNode(string xmlFileName, string xPath, string nodeName)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    if (xmlnode.HasChildNodes)
                    {
                        isSuccess = false;
                    }
                    else
                    {
                        xmlnode.ParentNode.RemoveChild(xmlnode);//删除节点
                        isSuccess = true;
                        xmldocument.Save(xmlFileName);
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return isSuccess;
        }
        /// <summary>
        /// 根据指定节点名称更新其下指定的子节点的值
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xPath"></param>
        /// <param name="nodeName"></param>
        /// <param name="innerText"></param>
        /// <returns></returns>
        public static bool UpdateChildNode(string xmlFileName, string xPath, string nodeName,string childName, string innerText)
        {
            bool isSuccess = false;
            XmlDocument xmldocument = new XmlDocument();
            try
            {
                XmlNode xmlnode = xmldocument.SelectSingleNode(xPath);
                if (xmlnode != null)
                {
                    foreach (XmlNode node in xmlnode.ChildNodes)
                    {
                        if (node.Name.ToLower() == childName.ToLower())
                        {
                            node.InnerText = innerText;
                            xmldocument.Save(xmlFileName);
                            isSuccess = true;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                throw err;
            }
            return isSuccess;
        }

#region 创建XML的根节点
        /// <summary>
        /// 创建XML的根节点
        /// </summary>
        private void CreateXMLElement()
        {

//创建一个XML对象
            _xml = new XmlDocument();

if (File.Exists(_FilePath))
            {
                //加载XML文件
                _xml.Load(this._FilePath);
            }

//为XML的根节点赋值
            _element = _xml.DocumentElement;
        }
        #endregion

#region 保存XML文件
        /// <summary>
        /// 保存XML文件
        /// </summary>       
        public void Save()
        {
            //创建XML的根节点
            //CreateXMLElement();

//保存XML文件
            _xml.Save(this._FilePath);
        }
        #endregion //保存XML文件

#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>
        public static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string version, string encoding, string standalone)
        {
            bool isSuccess = false;
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
                XmlNode root = xmlDoc.CreateElement(rootNodeName);
                xmlDoc.AppendChild(xmlDeclaration);
                xmlDoc.AppendChild(root);
                xmlDoc.Save(xmlFileName);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }
        #endregion
    }
}

c# xml操作类的更多相关文章

  1. 简单的XML操作类

    /// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { pr ...

  2. C#常用操作类库三(XML操作类)

    /// <summary> /// XmlHelper 的摘要说明. /// xml操作类 /// </summary> public class XmlHelper { pr ...

  3. XML Helper XML操作类

    写的一个XML操作类,包括读取/插入/修改/删除. using System;using System.Data;using System.Configuration;using System.Web ...

  4. C#对XML操作类

    C#对XML操作类 该类包含了对XML文件的创建,添加,读取,删除,修改等操作 //#define isUnity #if isUnity using UnityEngine; #endif usin ...

  5. PHP XML操作类DOMDocument

    不得不自已写一个.XML 的操作一直没有用过.下面是自己搜集的XML操作类 DOMDocument相关的内容. 属性: Attributes 存储节点的属性列表(只读) childNodes 存储节点 ...

  6. C#:XML操作类

    写的一个XML操作类,包括读取/插入/修改/删除. using System; using System.Data; using System.Configuration; using System. ...

  7. c# xml操作类 比较齐全

    using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...

  8. c#XML操作类的方法总结

    using System.Xml;using System.Data; namespace DotNet.Utilities{    /// <summary>    /// Xml的操作 ...

  9. XML操作类

        using System; using System.Data; using System.IO; using System.Xml; namespace DotNet.Utilities { ...

随机推荐

  1. Yii console 创建命令行应用

    大家都知道PHP的程序没有进程概念,而且生命周期极短,无法实现一些定时计划或者是计划任务,今天我们看看在YII框架中如何使用计划任务创建命令行应用. 1.在 console/controllers 文 ...

  2. 正式学习React(一) 开始学习之前必读

    为什么要加这个必读!因为webpack本身是基于node环境的, 里面会涉及很多路径问题,我们可能对paths怎么写!webpack又是怎么找到这些paths的很迷惑. 本文是我已经写完正式学习Rea ...

  3. Linux下 nginx + 最新版php5.5 安装配置详解

    1.nginx的安装: 首先nginx的安装需要依赖最基础的三个包,这里面我们不设计更多的扩展模块,只是安装最基础的三个包, zlib 此包主要是对http内容进行gzip压缩,减少网络传输流量 PC ...

  4. PDM使用问题总结

    1.连接postgres生成pdm 直接连postgres数据库生成的可以生成表名,但表结构为空,不知为何,后来直接用生成数据库sql脚本后转成pdm成功.但是列注释没有了. 2.sql语句生成的pd ...

  5. MFC子窗口和父窗口(SetParent,SetOwner)

    一.概念和区别 在windows系统中,每个窗口对象都对应有一个数据结构,形成一个list链表.系统的窗口管理器通过这个list来获取窗口信息和管理每个窗口.这个数据结构中有四个数据用来构建list, ...

  6. Windows去掉桌面SVN文件或文件夹问号

    将版本库 的内容检出 到桌面,后才发现桌面上的文件 都变成了问号,本来也以为没有多大问题,删除 .svn 即可,可是删除所有的.svn后,桌面上还是显示问号,刷新了很多次,还重启电脑 了,问号也没有消 ...

  7. Tengine笔记2:通过IP、域名、端口实现虚拟主机

    一.通过端口创建虚拟主机 案例:通过端口访问两个不同的页面 将/usr/local/tengine-2.1.0/html/index.html内的内容改为 Welcom to port1 然后在/op ...

  8. 创建渐进式jpeg图片

    <?php // Create an image instance $im = imagecreatefromjpeg('test.jpg');   // Enable interlancing ...

  9. OC基础2:一些基本概念

    "OC基础"这个分类的文章是我在自学Stephen G.Kochan的<Objective-C程序设计第6版>过程中的笔记. 1.字符常量是存放在单引号中的单个字符,字 ...

  10. Invalid file permission Please regenerate them with cacaoadm create-keys --force

    1.服务器重启之后,启动cacao报错,提示无效的文件权限. [root@ldapserver bin]# ./cacaoadm start Invalid file permission: [/ho ...