• xml帮助类


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.IO;
    using System.Data;
    using System.Collections;
    
    namespace PTool
    {
        /// <summary>
        /// 
        /// </summary>
        public class XMLFileHelper
        {
            /// <summary>
            /// 文件路径
            /// </summary>
            protected string _strfile = string.Empty;
    
            public XmlElement RootElement
            {
                get { return _xmldoc.DocumentElement; }
            }
    
            /// <summary>
            /// 
            /// </summary>
            protected XmlDocument _xmldoc = null;
    
            #region 构造函数  
    
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="XmlFile">xml文件路径</param>
            public XMLFileHelper(string strfile)
            {
                _strfile = strfile;
                if (File.Exists(_strfile))
                {
                    _xmldoc = new System.Xml.XmlDocument();
                    _xmldoc.Load(_strfile);
                }
                else
                {
                    _xmldoc = new System.Xml.XmlDocument();
                    XmlNode  xmlnode = _xmldoc.CreateNode ( XmlNodeType.XmlDeclaration , "" , "" ) ;
                    _xmldoc.AppendChild(xmlnode); 
                }
            }
            
    
            #endregion
    
            #region 属性  XmlDoc 
            
            /// <summary>
            ///  XmlDocument
            /// </summary>
            public XmlDocument XmlDoc
            {
                get { return _xmldoc; }
                set { _xmldoc = value; }
            }
            
            /// <summary>
            /// xml路径
            /// </summary>
            public string StrXmlFile
            {
                get { return _strfile; }
            }
         
            #endregion
    
            #region 返回节点数据   GetPathNodeValue(string pathNode), )GetDatatable(string PathNode),GetDataSet(string PathNode)
            
            /// <summary>
            /// 功能:
            /// 获取所有指定名称的节点(XmlNodeList)
            /// </summary>
            /// <param >节点名称</param>
            public XmlNodeList GetNodeList(string pathNode)
            {
                XmlNodeList strReturn = null;
                try
                {
                    //根据指定路径获取节点
                    XmlNodeList xmlNode = _xmldoc.SelectNodes(pathNode);
                    if (!(xmlNode == null))
                    {
                        strReturn = xmlNode;
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
                return strReturn;
            }
            
            #endregion
    
            #region 添加节点
    
            /// <summary>
            /// 插入一節點和此節點的一子節點。
            /// </summary>
            /// <param name="mainNode">主节点路径</param>
            /// <param name="childNode">插入的节点</param>
            /// <param name="element">插入的子节点</param>
            /// <param name="elementValue">子节点的值</param>
            public void InsertNode(string mainNode, string childNode, string element, string elementValue)
            {
    
                XmlNode objRootNode = _xmldoc.SelectSingleNode(mainNode);
                XmlElement objChildNode = _xmldoc.CreateElement(childNode);
                objRootNode.AppendChild(objChildNode);
                XmlElement objElement = _xmldoc.CreateElement(element);
                objElement.InnerText = elementValue;
                objChildNode.AppendChild(objElement);
            }
            
            /// <summary>
            /// 插入一個節點,帶1屬性。
            /// </summary>
            /// <param name="mainNode">节点路径</param>
            /// <param name="node">插入节点名称</param>
            /// <param name="nodeValue">节点值</param>
            /// <param name="attrib">节点属性名称</param>
            /// <param name="attribValue">节点属性的值</param>
            public void InsertNode(string mainNode, string node, string nodeValue, string attrib, string attribValue)
            {
    
                XmlNode objNode = _xmldoc.SelectSingleNode(mainNode);
                XmlElement objElement = _xmldoc.CreateElement(node);
                objElement.SetAttribute(attrib, attribValue);
                objElement.InnerText = nodeValue;
                objNode.AppendChild(objElement);
            }
            
            /// <summary>
            /// 插入一個節點,帶2屬性。
            /// </summary>
            /// <param name="mainNode">节点路径</param>
            /// <param name="node">插入节点名称</param>
            /// <param name="nodeValue">节点值</param>
            /// <param name="attrib1">节点属性名称1</param>
            /// <param name="attribContent1">节点属性的值1</param>
            /// <param name="attrib2">节点属性名称2</param>
            /// <param name="attribContent2">节点属性的值2</param>
            public void InsertNode(string mainNode, string node, string nodeValue, string attrib1, string attribContent1, string attrib2, string attribContent2)
            {
    
                XmlNode objNode = _xmldoc.SelectSingleNode(mainNode);
                XmlElement objElement = _xmldoc.CreateElement(node);
                objElement.SetAttribute(attrib1, attribContent1);
                objElement.SetAttribute(attrib2, attribContent2);
                objElement.InnerText = nodeValue;
                objNode.AppendChild(objElement);
            }
    
            /// <summary>
            /// 插入一個節點,不帶屬性
            /// </summary>
            /// <param name="mainNode">节点路径</param>
            /// <param name="node">节点名称</param>
            /// <param name="nodeValue">节点的值</param>
            public XmlNode InsertNode(string mainNode, string node, string nodeValue)
            {
                XmlNode objNode = _xmldoc.SelectSingleNode(mainNode);
                XmlElement objElement = _xmldoc.CreateElement(node);
                objElement.InnerText = nodeValue;
                objNode.AppendChild(objElement);
                return objElement;
            }
            
            /// <summary>
            /// 插入一個節點,不帶屬性
            /// </summary>
            /// <param name="mainNode">节点路径</param>
            /// <param name="node">节点名称</param>
            /// <param name="nodeInde">节点索引</param>
            /// <param name="nodeValue">节点的值</param>
            public void InsertNode(string mainNode, int mainNodeIndex, string node, string nodeValue)
            {
    
                XmlNode objNode = _xmldoc.SelectNodes(mainNode).Item(mainNodeIndex);
                XmlElement objElement = _xmldoc.CreateElement(node);
                objElement.InnerText = nodeValue;
                objNode.AppendChild(objElement);
            }
    
            ///// <summary>
            ///// 插入一個節點,设置为空值
            ///// </summary>
            ///// <param name="mainNode"></param>
            ///// <param name="pathNode"></param>
            //public void AddAttribute(XmlNode objNode,string key, string value)
            //{
            //    return InsertNode(mainNode, pathNode, "");
            //}
            #endregion
    
            public XmlNode InsertNode(string mainNode, string pathNode)
            {
                return InsertNode(mainNode, pathNode, "");
            }
    
            #region 更新节点和属性
            //更新節點內容。
            /// <summary>
            /// 根据节点路径更新節點內容。
            /// </summary>
            /// <param name="pathNode">节点路径</param>
            /// <param name="nodeValue">节点值</param>
            public void Replace(string pathNode, string nodeValue)
            {
                _xmldoc.SelectSingleNode(pathNode).InnerText = nodeValue;
            }
    
    
            /// <summary>
            /// 功能:
            /// 设置节点的属性值
            /// </summary>
            /// <param name="pathNode"></param>
            /// <param name="nodeAttribute"></param>
            /// <param name="nodeAttributeValue"></param>
            public void SetNodeAttributeValue(string pathNode, string nodeAttribute, string nodeAttributeValue)
            {
                try
                {
                    //可以批量为符合条件的节点的属性付值
                    XmlNodeList xmlNode = this._xmldoc.SelectNodes(pathNode);
                    if (!(xmlNode == null))
                    {
                        foreach (XmlNode xn in xmlNode)
                        {
                            XmlAttributeCollection xmlAttr = xn.Attributes;
                            for (int i = 0; i < xmlAttr.Count; i++)
                            {
                                if (xmlAttr.Item(i).Name == nodeAttribute)
                                {
                                    xmlAttr.Item(i).Value = nodeAttributeValue;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
            }
            #endregion
    
    
            /// <summary>
            /// 检查节点是否存在
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            public bool ExistNode(string node)
            {
                if (_xmldoc.SelectSingleNode(node) == null)
                    return false;
                return true;
            }
            
            /// <summary>
            /// 查找某个节点的数量
            /// </summary>
            /// <param name="elementName"></param>
            /// <returns></returns>
            public int SelectElements(string elementName)
            {
                return _xmldoc.GetElementsByTagName(elementName).Count;
            }
    
            #region 删除节点 属性
    
            // 删除节点
            /// <summary>
            /// 删除节点
            /// </summary>
            /// <param name="NodePath">节点路径</param>
            public void DeleteNode(string NodePath)
            {
                XmlNodeList nodePath = this._xmldoc.SelectNodes(NodePath);
                if (!(nodePath == null))
                {
                    foreach (XmlNode xn in nodePath)
                    {
                        xn.ParentNode.RemoveChild(xn);
                    }
                }
            }
    
            /// <summary>
            /// 删除指定路径的所有子节点和属性
            /// </summary>
            /// <param name="ParentPath">父节点路径</param>
            public void DeleteChildNode(string ParentPath)
            {
    
                XmlNodeList ResultNodes = _xmldoc.SelectNodes(ParentPath);
                if (!(ResultNodes == null))
                {
                    foreach (XmlNode xn in ResultNodes)
                    {
                        xn.RemoveAll();
                    }
                }
    
            }
            /// <summary>
            /// 删除节点的一个属性
            /// </summary>
            /// <param >节点所在的xpath表达式</param>
            /// <param >属性名</param>
            public void DeleteAttribute(string NodePath, string NodeAttribute)
            {
                XmlNodeList nodePath = this._xmldoc.SelectNodes(NodePath);
                if (!(nodePath == null))
                {
                    foreach (XmlNode tempxn in nodePath)
                    {
                        XmlAttributeCollection xmlAttr = tempxn.Attributes;
                        for (int i = 0; i < xmlAttr.Count; i++)
                        {
                            if (xmlAttr.Item(i).Name == NodeAttribute)
                            {
                                tempxn.Attributes.RemoveAt(i);
                                break;
                            }
                        }
                    }
                }
            }
    
            /// <summary>
            /// 删除节点的一个属性,当其属性值等于给定的值时
            /// </summary>
            /// <param >节点所在的xpath表达式</param>
            /// <param >属性</param>
            /// <param ></param>
            public void DeleteAttribute(string NodePath, string NodeAttribute, string NodeAttributeValue)
            {
                XmlNodeList nodePath = this._xmldoc.SelectNodes(NodePath);
                if (!(nodePath == null))
                {
                    foreach (XmlNode tempxn in nodePath)
                    {
                        XmlAttributeCollection xmlAttr = tempxn.Attributes;
                        for (int i = 0; i < xmlAttr.Count; i++)
                        {
                            if (xmlAttr.Item(i).Name == NodeAttribute && xmlAttr.Item(i).Value == NodeAttributeValue)
                            {
                                tempxn.Attributes.RemoveAt(i);
                                break;
                            }
                        }
                    }
                }
            }
    
            #endregion
    
    
            /// <summary>
            /// 或得指定查询节点得子节点数目
            /// </summary>
            /// <param name="pathNode">节点路径</param>
            /// <returns></returns>
            public int ChildCount(string pathNode)
            {
                try
                {
                    XmlNode ResultNodes = _xmldoc.SelectSingleNode(pathNode);
                    return ResultNodes.ChildNodes.Count;
    
                }
                catch
                {
                    return -1;
    
                }
    
            }
    
            #region 保存
            //保存文檔
            /// <summary>
            /// 保存并关闭文档
            /// </summary>
            public void Save()
            {
                try
                {
                    _xmldoc.Save(_strfile);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
    
            }
    
    
            /// <summary>
            ///  关闭文档
            /// </summary>
            public void Close()
            {
                _xmldoc = null;
            }
    
            #endregion
    
            #region 读取指定节点的指定属性值
            /**/
            /// <summary>
            /// 功能:
            /// 读取指定节点的指定属性值    
            /// </summary>
            /// <param name="pathNode">节点名称</param>
            /// <param name="strAttribute">此节点的属性</param>
            /// <returns></returns>
            public string GetNodeAttributeValue(string pathNode, string strAttribute)
            {
                string strReturn = "";
                try
                {
                    //根据指定路径获取节点
                    XmlNode xmlNode = _xmldoc.SelectSingleNode(pathNode);
                    if (!(xmlNode == null))
                    {//获取节点的属性,并循环取出需要的属性值
                        XmlAttributeCollection xmlAttr = xmlNode.Attributes;
    
                        for (int i = 0; i < xmlAttr.Count; i++)
                        {
                            if (xmlAttr.Item(i).Name == strAttribute)
                            {
                                strReturn = xmlAttr.Item(i).Value;
                                break;
                            }
                        }
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
                return strReturn;
            }
            #endregion
    
            #region 向节点添加属性
            /// <summary>
            /// 向一个节点添加属性,值为空
            /// </summary>
            /// <param >节点路径</param>
            /// <param >属性名</param>
            public void AddAttribute(string NodePath, string NodeAttribute)
            {
                AddAttributeEx(NodePath, NodeAttribute, "");
            }
    
    
            /// <summary>
            /// 向一个节点添加属性,并赋值***
            /// </summary>
            public void AddAttribute(XmlNode childXmlNode, string NodeAttribute, string NodeAttributeValue)
            {
                XmlAttribute nodeAttribute = this._xmldoc.CreateAttribute(NodeAttribute);
                nodeAttribute.Value = NodeAttributeValue;
                childXmlNode.Attributes.Append(nodeAttribute);
            }
    
            /// <summary>
            /// 向一个节点添加属性
            /// </summary>
            /// <param >节点路径</param>
            /// <param >属性名</param>
            /// <param >属性值</param>
            private void AddAttributeEx(string NodePath, string NodeAttribute, string NodeAttributeValue)
            {
                try
                {
                    XmlNode nodePath = _xmldoc.SelectSingleNode(NodePath);
                    if (!(nodePath == null))
                    {
                        XmlAttribute nodeAttribute = this._xmldoc.CreateAttribute(NodeAttribute);
                        nodeAttribute.Value = NodeAttributeValue;
                        nodePath.Attributes.Append(nodeAttribute);
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
            }
    
            #endregion
    
    
            #region dataset 操作 xml
            
            /// <summary>
            /// 从XML文件中读到数据表中
            /// </summary>
            /// <param name="sXmlFile"></param>
            /// <returns></returns>
            public DataTable ReadXmlFileToDataTable(string sXmlFile)
            {
    
                try
                {
                    DataSet dst = new DataSet();
                    dst.ReadXml(sXmlFile);
                    DataTable dt = dst.Tables[0];
                    return dt;
                }
                catch
                {
                    return null;
                }
            }
    
            /// <summary>
            /// 将数据表写入XML文件
            /// </summary>
            /// <param name="dt"></param>
            /// <param name="sXmlFile"></param>
            /// <returns></returns>
            public bool SaveDataTableToXmlFile(DataTable dt, string sXmlFile)
            {
                if (dt == null)
                {
                    return false;
                }
    
                try
                {
                    DataSet dst = new DataSet();
                    dst.Tables.Add(dt);
                    dst.WriteXml(sXmlFile, XmlWriteMode.WriteSchema);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
    
    
            /// <summary>
            /// 查找數據。返回一個Datatable(单个)
            /// </summary>
            /// <param name="pathNode">节点路径</param>
            /// <returns></returns>
            public DataTable GetDatatable(string pathNode)
            {
                DataSet ds = new DataSet();
                XmlNode Node = _xmldoc.SelectSingleNode(pathNode);
                StringReader read = new StringReader(Node.OuterXml);
                //StringReader read = new StringReader(xmlDoc.SelectSingleNode(pathNode).OuterXml);
    
                ds.ReadXml(read);
                return ds.Tables[0];
            }
    
            /// <summary>
            /// 查找节点,返回一个只包含一Row的DataTable
            /// </summary>
            /// <param name="XPath">节点路径</param>
            /// <returns></returns>
            public DataTable GetSingleRowDatatable(string XPath)
            {
                DataTable Dt = new DataTable();
                DataRow Dr = Dt.NewRow();
    
                XmlNode SingleNode = _xmldoc.SelectSingleNode(XPath);
                foreach (XmlNode Node in SingleNode.ChildNodes)
                {
    
                    if (!Dt.Columns.Contains(Node.Name))
                    {
                        Dt.Columns.Add(Node.Name);
                    }
                    Dr[Node.Name] = Node.InnerText;
                }
                Dt.Rows.Add(Dr);
                return Dt;
            }
    
    
            /// <summary>
            /// 查找节点 返回包含多Row的DataTable
            /// </summary>
            /// <param name="XPath">节点路径</param>
            /// <returns>DataTable</returns>
            public DataTable GetMultipleRowDatatable(string XPath)
            {
                DataTable Dt = new DataTable();
                DataRow Dr;
                XmlNodeList NodeList = _xmldoc.SelectNodes(XPath);
                foreach (XmlNode Node in NodeList)
                {
                    Dr = Dt.NewRow();
                    foreach (XmlNode node in Node.ChildNodes)
                    {
                        if (!Dt.Columns.Contains(node.Name))
                        {
                            Dt.Columns.Add(node.Name);
                        }
                        Dr[node.Name] = node.InnerText;
                    }
                    Dt.Rows.Add(Dr);
                }
                return Dt;
            }
    
            /// <summary>
            /// 查找數據。返回一個DataSet(多个)
            /// </summary>
            /// <param name="pathNode">节点路径</param>
            /// <returns></returns>
            public DataSet GetDataSet(string pathNode)
            {
                DataSet ds = new DataSet();
    
                foreach (XmlNode xmlnode in _xmldoc.SelectNodes(pathNode))
                {
                    StringReader read = new StringReader(xmlnode.OuterXml);
                    ds.ReadXml(read);
                }
                return ds;
            }
            
            /// <summary>
            /// 将datatalbe 存放到parentPathNode节点下
            /// </summary>
            /// <param name="parentPathNode">父节点路径</param>
            /// <param name="dt">datatable</param>
            /// <returns></returns>
            public bool SaveDataTableToNode(string parentPathNode, DataTable dt)
            {
                int rows = dt.Rows.Count;
                int cols = dt.Columns.Count;
                DeleteChildNode(parentPathNode);
    
                if (!ExistNode(parentPathNode))
                    return false;
                for (int row = 0; row < rows; row++)
                {
                    InsertNode(parentPathNode, dt.TableName);
                    for (int col = 0; col < cols; col++)
                    {
                        InsertNode(parentPathNode + "/" + dt.TableName, row, dt.Columns[col].Caption, dt.Rows[row][col].ToString());
                    }
                }
                return true;
            }
    
            #endregion
    
            /// <summary>
            /// 把给定字符串转换成国标码
            /// </summary>
            /// <param name="Str">给定字符序列</param>
            /// <returns>国标码字符序列</returns>
            public string GetGB2312(string Str)
            {
                byte[] bytes = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(Str);
                string sTraditional = System.Text.Encoding.GetEncoding("GB2312").GetString(bytes);
                return sTraditional;
            }
    
            #region 单一节点的读 写
            public string GetNodeValue(string XPath)
            {
                string strReturn = string.Empty;
                try
                {
                    //根据指定路径获取节点
                    XmlNode xmlNode = _xmldoc.SelectSingleNode(XPath);
                    if (xmlNode != null)
                    {
                        //获取节点的值
                        strReturn = xmlNode.InnerText;
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
                return strReturn;
            }
            
    
             public string GetNodeValue(string pathNode,string value)
            {
                string strReturn = "";
                try
                {
                    //根据指定路径获取节点
                    XmlNodeList xmlNode = _xmldoc.SelectNodes(pathNode);//.Item.SelectSingleNode(value);
                    //if (xmlNode != null)
                    //{
                    //    //获取节点的值
                    //    strReturn = xmlNode.InnerText;
                    //}
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
                return strReturn;
            }
            /// <summary>
            /// 功能:
            /// 设置节点值        
            /// </summary>
            /// <param name="pathNode">节点的名称</param>
            /// <param name="nodeValue">节点值</param>
            public void SetNodeValue(string XPath, string nodeValue)
            {
                try
                {
                    //可以批量为符合条件的节点进行付值
                    XmlNode xmlNode = this._xmldoc.SelectSingleNode(XPath);
                    if (xmlNode != null)
                    {
                        xmlNode.InnerText = nodeValue;
                    }
                    else
                    {
                        string strnode = XPath.Substring(0,XPath.LastIndexOf("/"));
                        XmlNode xmlPathNode = this._xmldoc.SelectSingleNode(strnode);
                        if (xmlPathNode != null)
                        {
                            string strchildnode = XPath.Substring(XPath.LastIndexOf("/") + 1, XPath.Length - XPath.LastIndexOf("/") - 1);
                            XmlElement objElement = _xmldoc.CreateElement(strchildnode);
                            if (objElement != null)
                            {
                                objElement.InnerText = nodeValue;
                                xmlPathNode.AppendChild(objElement);
                            }
                        }
                    }
                }
                catch (XmlException xmle)
                {
                    throw xmle;
                }
            }
            #endregion
    
            public void CreateNode(string node)
            {
                if (!ExistNode(node))
                {
                    XmlDocument myXml = new XmlDocument();
                    XmlElement xe = myXml.CreateElement(node);
                    _xmldoc.AppendChild(_xmldoc.ImportNode(xe,false));
                }
            }
    
        }
    }

    调用

     public  void CreateXml()
            {
                XMLFileHelper xml = new XMLFileHelper(xmlurl);
                XmlNodeList nodelist = xml.GetNodeList("root/wsmodel");
                CreateParaCollectionList(nodelist);
            }
    CreateParaCollectionList

         private  void CreateParaCollectionList(XmlNodeList nodelist)
            {
                if (nodelist != null)
                {
                    if (_paramcollection == null)
                    {
                        _paramcollection = new List<WSCollectionModel>();
                    }
                    foreach (XmlNode item in nodelist)
                    {
                        WSCollectionModel model = new WSCollectionModel();
                        if (!DBConvert.IsDBNull(item.Attributes["FunctionName"]))
                        {
                            model.Function_name = DBConvert.ToString(item.Attributes["FunctionName"].InnerText);
                        }
                        if (!DBConvert.IsDBNull(item.Attributes["ClassName"]))
                        {
                            model.Class_name = DBConvert.ToString(item.Attributes["ClassName"].InnerText);
                        }
                        if (!DBConvert.IsDBNull(item.Attributes["NameSpace"]))
                        {
                            model.Name_space = DBConvert.ToString(item.Attributes["NameSpace"].InnerText);
                        }
                        if (!DBConvert.IsDBNull(item.Attributes["WsUrl"]))
                        {
                            model.Ws_url = DBConvert.ToString(item.Attributes["WsUrl"].InnerText);
                        }
                        _paramcollection.Add(model);
                    }
    
                }
    
            }
    萌橙 你瞅啥?
  • 相关阅读:
    树莓派4B对接苹果Homebrigde
    分享一款好看的PyCharm风格(转)
    Centos7安装opencv-python缺少共享库(libSM.so.6, libXrender.so.1, libXext.so.6)的解决办法
    win10 python3.7安装 opencv 和 face_recognition
    Python出现Could not find a version that satisfies the requirement openpyxl (from versions: )
    从零开始开发标准的s57电子海图第十三篇 电子海图中特征记录各字段结构和内容(共一百篇)
    从零开始开发标准的s57电子海图第十二篇 编码原则与记录结构(共一百篇)
    从零开始开发标准的s57电子海图第十一篇--海图文件中的数据类型(共一百篇)
    从零开始开发标准的s57电子海图第十篇--海图文件示例(共一百篇)
    从零开始开发标准的s57电子海图第九篇--数据记录字段DR区的结构(共一百篇)
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/11242152.html
Copyright © 2020-2023  润新知