致力于技术进步

专注于编程艺术

博客园 首页 新随笔 联系 订阅 管理


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

namespace Ahedu.Common
{
    /// <summary>
    /// 提供操作XML文件的类
    /// </summary>
    public class XMLHelper
    {
        #region Constructor
        public XMLHelper()
        { }
        #endregion

        #region 在根节点下添加父节点
        /// <summary>
        /// 在根节点下添加父节点
        /// </summary>
        /// <param name="xmlPath">xml文件路径</param>
        /// <param name="parentNode">节点的名字</param>
        public bool AddParentNode(string xmlPath, string parentNode)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(@xmlPath);
                XmlElement node = objXmlDoc.CreateElement(parentNode);
                objXmlDoc.DocumentElement.PrependChild(node);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 插入一节点,带一属性
        /// <summary>
        /// 插入一节点,带一属性
        /// </summary>
        /// <param name="xmlPath">xml文档路径</param>
        /// <param name="MainNode">当前节点路径(xpath)</param>
        /// <param name="Element">新节点</param>
        /// <param name="Attib">属性名称</param>
        /// <param name="AttribContent">属性值</param>
        /// <param name="Content">新节点值</param>
        public bool XmlInsertElement(string xmlPath, string MainNode, string
            Element, string Attib, string AttribContent, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(@xmlPath);
                XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXmlDoc.CreateElement(Element);
                objElement.SetAttribute(Attib, AttribContent);
                objElement.InnerText = Content;
                objNode.AppendChild(objElement);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;

        }
        #endregion

        #region 创建一个有节点的XML文件
        /// <summary>
        /// 新建一个XML文件,只有document节点和其子节点title
        /// </summary>
        /// <param name="XmlPath">待创建文件的路径,包括文件名和XML扩展名</param>
        public bool CreatXmlFile(string XmlPath)
        {
            try
            {
                XmlTextWriter writer = new XmlTextWriter((XmlPath), Encoding.UTF8);
                writer.WriteStartDocument();
                writer.WriteStartElement("document");
                writer.WriteStartElement("title");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
                return true;
            }
            catch (Exception Ex)
            {
                return false;
            }
        }
        #endregion

        #region 插入一个不带属性的节点
        /// <summary>
        /// 插入一个不带属性的节点
        /// </summary>
        /// <param name="xmlPath">xml文档路径</param>
        /// <param name="MainNode">当前节点路径(xpath)</param>
        /// <param name="Element">新节点</param>
        /// <param name="Content">新节点值</param>
        public bool XmlInsertElement(string xmlPath, string MainNode, string Element, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(@xmlPath);
                XmlNode objNode = objXmlDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXmlDoc.CreateElement(Element);
                objElement.InnerText = Content;
                objNode.AppendChild(objElement);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;

        }
        #endregion

        #region 插入一个节点和此节点的字节点

        /// <summary>
        /// 插入一个节点和此节点的字节点
        /// </summary>
        /// <param name="xmlPath">xml路径</param>
        /// <param name="MailNode">当前节点路径</param>
        /// <param name="ChildNode">新插入节点</param>
        /// <param name="InnerText">元素的名称和值</param>
        /// <returns>true:插入成功 ,false:插入失败</returns>
        public bool XmlInsertNode(string xmlPath, string MailNode, string ChildNode, string[,] InnerText)
        {

            XmlDocument objXmlDoc = new XmlDocument();

            try
            {
                objXmlDoc.Load(xmlPath);
                XmlNode objRootNode = objXmlDoc.SelectSingleNode(MailNode);
                XmlElement objChildNode = objXmlDoc.CreateElement(ChildNode);
                objRootNode.AppendChild(objChildNode);
                for (int i = 0; i < InnerText.Length / 2; i++)
                {
                    XmlElement objElement = objXmlDoc.CreateElement(InnerText[i, 0]);
                    objElement.InnerText = InnerText[i, 1];
                    objChildNode.AppendChild(objElement);
                }
                objXmlDoc.Save(xmlPath);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }


        }
        /// <summary>
        /// 插入一个节点和此节点的字节点
        /// </summary>
        /// <param name="xmlPath">xml路径</param>
        /// <param name="MailNode">当前节点路径</param>
        /// <param name="ChildNode">新插入节点</param>
        /// <param name="Element">插入节点的子节点</param>
        /// <param name="Content">子节点的内容</param>
        public bool XmlInsertNode(string xmlPath, string MailNode, string ChildNode, string Element, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();

            try
            {
                objXmlDoc.Load(xmlPath);
                XmlNode objRootNode = objXmlDoc.SelectSingleNode(MailNode);
                XmlElement objChildNode = objXmlDoc.CreateElement(ChildNode);
                objRootNode.AppendChild(objChildNode);
                XmlElement objElement = objXmlDoc.CreateElement(Element);
                objElement.InnerText = Content;
                objChildNode.AppendChild(objElement);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
        #endregion

        #region 删除xml节点和此节点下的子节点
        /// <summary>
        /// 删除xml节点和此节点下的子节点
        /// </summary>
        /// <param name="xmlPath">xml文档路径</param>
        /// <param name="Node">节点路径(xpath)</param>
        public bool XmlNodeDelete(string xmlPath, string Node)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(xmlPath);
                //string mainNode = Node.Substring(0, Node.LastIndexOf("/"));
                XmlNode xn = objXmlDoc.DocumentElement;
                XmlNode node = objXmlDoc.SelectSingleNode(Node).ParentNode;
                //objXmlDoc.node.RemoveChild(objXmlDoc.SelectSingleNode(Node));
                xn.RemoveChild(node);
               objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 删除一个节点的属性
        /// <summary>
        /// 删除一个节点的属性
        /// </summary>
        /// <param name="xmlPath">xml文件路径</param>
        /// <param name="NodePath">节点路径(xpath)</param>
        /// <param name="NodeAttribute"></param>
        public bool xmlNodeAttributeDel(string xmlPath, string NodePath, string NodeAttribute)
        {
            XmlDocument objXmlDoc = new XmlDocument();

            try
            {
                objXmlDoc.Load(@xmlPath);
                XmlNode nodePath = objXmlDoc.SelectSingleNode(NodePath);
                XmlElement xe = (XmlElement)nodePath;
                xe.RemoveAttribute(NodeAttribute);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;


        }
        #endregion

        #region 更新xml节点内容
        /// <summary>
        /// 更新xml节点内容
        /// </summary>
        /// <param name="xmlPath">xml路径</param>
        /// <param name="Node">要更换内容的节点:节点路径/父节点/当前节点(xpath)</param>
        /// <param name="Content">新的内容</param>
        public bool XmlNodeReplace(string xmlPath, string Node, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(xmlPath);
                objXmlDoc.SelectSingleNode(Node).InnerText = Content;
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;

        }
        #endregion

        #region 更改节点的属性值
        /// <summary>
        /// 更改节点的属性值
        /// </summary>
        /// <param name="xmlPath">XML文件路径</param>
        /// <param name="NodePath">节点路径(XPath)</param>
        /// <param name="NodeAttributeName">要更改的节点属性的名称</param>
        /// <param name="NodeAttributeText">更改的属性值</param>
        public bool XmlAttributeEdit(string xmlPath, string NodePath, string NodeAttributeName, string NodeAttributeText)
        {
            XmlDocument objXmlDoc = new XmlDocument();

            try
            {
                objXmlDoc.Load(@xmlPath);
                XmlNode node = objXmlDoc.SelectSingleNode(NodePath);
                XmlElement xe = (XmlElement)node;
                xe.SetAttribute(NodeAttributeName, NodeAttributeText);
                objXmlDoc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;


        }
        #endregion

        #region 读取XML到DataSet
        /// <summary>
        /// 读取XML到DataSet
        /// </summary>
        /// <param name="XmlPath">xml文档路径</param>
        /// <returns></returns>
        public DataSet GetXml(string XmlPath)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(@XmlPath);
            return ds;
        }
        #endregion

        #region 查找数据,返回当前节点的所有下级节点,填充到一个DataSet中
        /// <summary>
        /// 查找数据,返回当前节点的所有下级节点,填充到一个DataSet中
        /// </summary>
        /// <param name="xmlPath">xml文档路径</param>
        /// <param name="XmlPathNode">节点的路径:根节点/父节点/当前节点</param>
        /// <returns></returns>
        public DataSet GetXmlData(string xmlPath, string XmlPathNode)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(xmlPath);
                DataSet ds = new DataSet();
                StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml);
                ds.ReadXml(read);
                return ds;
            }
            catch (Exception ex)
            {
                return null;
            }


        }
        #endregion

        #region 根据ID读取符合该ID的记录信息()
        /// <summary>
        /// 根据ID读取符合该ID的记录信息
        /// </summary>
        /// <param name="xmlPath">xml文件路径</param>
        /// <param name="xPath">ID节点路径(xpath)</param>
        /// <returns></returns>
        public DataSet GetXmlDataByID(string xmlPath, string xPath)
        {

            XmlDocument objXmlDoc = new XmlDocument();

            try
            {

                objXmlDoc.Load(xmlPath);
                DataSet ds = new DataSet();
                XmlNode node = objXmlDoc.SelectSingleNode(xPath);
                XmlNodeReader reader = new XmlNodeReader(node);
                ds.ReadXml(reader);
                return ds;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region 读取指定节点的指定属性值
        /// <summary>
        /// 读取指定节点的指定属性值
        /// </summary>
        /// <param name="strNode">节点路径</param>
        /// <param name="strAttribute">此节点的属性</param>
        /// <returns></returns>
        public string GetXmlNodeAttribute(string xmlPath, string strNode, string strAttribute)
        {

            string strReturn = "";
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(xmlPath);

                //根据指定路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode);
                //获取节点的属性,并循环取出需要的属性值
                XmlAttributeCollection xmlAttr = xmlNode.Attributes;

                for (int i = 0; i < xmlAttr.Count; i++)
                {
                    if (xmlAttr.Item(i).Name == strAttribute)
                        strReturn = xmlAttr.Item(i).Value;
                }
                return strReturn;
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        #region 读取指定节点的值
        /// <summary>
        /// 读取指定节点的值
        /// </summary>
        /// <param name="strNode">节点名称(xpath)</param>
        /// <returns></returns>
        public string GetXmlNodeValue(string xmlPath, string strNode)
        {
            string strReturn = String.Empty;
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(xmlPath);

                //根据路径获取节点
                XmlNode xmlNode = xmlDoc.SelectSingleNode(strNode);
                strReturn = xmlNode.InnerText;
                return strReturn;
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }
        #endregion

        #region 根据节点属性读取子节点值(较省资源模式)
        /// <summary>
        /// 根据节点属性读取子节点值(较省资源模式)
        /// </summary>
        /// <param name="XmlPath">xml路径</param>
        /// <param name="FatherElement">父节点值</param>
        /// <param name="AttributeName">属性名称</param>
        /// <param name="AttributeValue">属性值</param>
        /// <param name="ArrayLength">返回的数组长度</param>
        /// <returns></returns>
        public System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElement, string AttributeName, string AttributeValue, int ArrayLength)
        {
            System.Collections.ArrayList al = new System.Collections.ArrayList();

            try
            {
                XmlDocument docXml = new XmlDocument();
                docXml.Load(XmlPath);
                XmlNodeList xn;
                xn = docXml.DocumentElement.SelectNodes("//" + FatherElement + "[" + @AttributeName + "='" + AttributeValue + "']");
                XmlNodeList xx = xn.Item(0).ChildNodes;
                for (int i = 0; i < ArrayLength & i < xx.Count; i++)
                {

                    al.Add(xx.Item(i).InnerText);
                }
                return al;
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }
        #endregion

        #region  更新指定用户的一个指定的节点值
        /// <summary>
        /// 更新指定用户的一个指定的节点值
        /// </summary>
        /// <param name="xmlPath">xml表地路径</param>
        /// <param name="userID">用户编号</param>
        /// <param name="node">修改的节点名</param>
        /// <param name="Content">修改的内容</param>
        /// <returns>true:修改成功;false:修改失败</returns>
        public bool UpdateNodeContentByID(string xmlPath, string userID, string node, string Content)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(xmlPath);
                XmlNodeList xmlnodelist = objXmlDoc.SelectSingleNode(objXmlDoc.DocumentElement.Name).ChildNodes;//得到根结点下面的所有第一级结点
                foreach (XmlNode xn in xmlnodelist)   //在第一级结点中遍历
                {
                    //XmlElement xe = (XmlElement)xn;  //将XmlNode 转换为XmlElement 类型
                    XmlNodeList list = xn.ChildNodes;
                    if (list[0].InnerText == userID)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i].Name == node)
                            {
                                list[i].InnerText = Content;
                                objXmlDoc.Save(xmlPath);  //保存
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion

        #region MW
        /// <summary>
        /// 删除给定节点值的节点及该节点上一级父节点
        /// </summary>
        /// <param name="xmlPath">xml表地路径</param>
        /// <param name="xmlNodeValue">给定节点值</param>
        /// <returns></returns>
        public bool DeleteXmlNode(string xmlPath, string xmlNodeValue)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            try
            {
                objXmlDoc.Load(xmlPath);
                //XmlNode xmlNode = doc.SelectSingleNode("MyTasks/Tasks/TaskID");
                XmlNodeList xmlnodelist = objXmlDoc.SelectSingleNode(objXmlDoc.DocumentElement.Name).ChildNodes;//得到根结点下面的所有第一级结点
                foreach (XmlNode xn1 in xmlnodelist) //遍历所有子节点
                {
                    XmlNodeList list = xn1.ChildNodes; //继续获取xn子节点的所有子节点
                    foreach (XmlNode xn2 in list)//遍历
                    {
                        XmlElement xe = (XmlElement)xn2;//转换类型
                        if (xe.Name == "TaskID" && xe.InnerText == xmlNodeValue) //如果找到
                        {
                            xn1.ParentNode.RemoveChild(xn1); //删除节点
                            objXmlDoc.Save(xmlPath);
                            break; //找到退出
                        }
                    }                   
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 选择用户表的数据
        /// </summary>
        /// <param name="xmlPath">xml表地路径</param>
        /// <returns></returns>
        public DataTable SelectAssigner(string xmlPath)
        {
            XmlDocument objXmlDoc = new XmlDocument();
            DataTable tbAssigner = new DataTable("AssignerTable");
            tbAssigner.Columns.Add("UserID", typeof(string));
            tbAssigner.Columns.Add("Name", typeof(string));
            tbAssigner.Columns.Add("Password", typeof(string));
            tbAssigner.Columns.Add("CreatedDate", typeof(string));
            tbAssigner.Columns.Add("Interval", typeof(string));
            tbAssigner.Columns.Add("DeletedSign", typeof(string));
            try
            {
                objXmlDoc.Load(xmlPath);
                XmlNodeList xmlnodelist = objXmlDoc.SelectSingleNode(objXmlDoc.DocumentElement.Name).ChildNodes;
                foreach (XmlNode xn1 in xmlnodelist)
                {
                    XmlNodeList list = xn1.ChildNodes;
                    if (list.Item(5).InnerText == "0")
                    {
                        DataRow dr = tbAssigner.NewRow();
                        foreach (XmlNode xn2 in list)
                        {
                            XmlElement xe = (XmlElement)xn2;
                            dr[xe.Name] = xe.InnerText;
                        }
                        tbAssigner.Rows.Add(dr);
                    }
                }
                return tbAssigner;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}

posted on 2009-12-14 19:11  stephen&amp;#183;周  阅读(238)  评论(0编辑  收藏  举报