| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773 | using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Windows.Forms;using System.Xml;namespace OTSCommon{    public class XMLoperate    {        #region 读取XML到DataSet        /// <summary>        /// 功能:读取XML到DataSet中        /// </summary>        /// <param name="XmlPath">xml路径</param>        /// <returns>DataSet</returns>        public static DataSet GetXml(string XmlPath)        {            DataSet ds = new DataSet();            ds.ReadXml(@XmlPath);            return ds;        }        #endregion        #region 读取xml文档并返回一个节点        /// <summary>        /// 读取xml文档并返回一个节点:适用于一级节点        /// </summary>        /// <param name="XmlPath">xml路径</param>        /// <param name="NodeName">节点</param>        /// <returns></returns>        public static string ReadXmlReturnNode(string XmlPath, string Node)        {            XmlDocument docXml = new XmlDocument();            docXml.Load(@XmlPath);            XmlNodeList xn = docXml.GetElementsByTagName(Node);            return xn.Item(0).InnerText.ToString();        }        #endregion        #region 查找数据,返回一个DataSet        /// <summary>        /// 查找数据,返回当前节点的所有下级节点,填充到一个DataSet中        /// </summary>        /// <param name="xmlPath">xml文档路径</param>        /// <param name="XmlPathNode">节点的路径:根节点/父节点/当前节点</param>        /// <returns></returns>        public static DataSet GetXmlData(string xmlPath, string XmlPathNode)        {            XmlDocument objXmlDoc = new XmlDocument();            objXmlDoc.Load(xmlPath);            DataSet ds = new DataSet();            StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml);            ds.ReadXml(read);            return ds;        }        #endregion        //必须创建对象才能使用的类        private bool _alreadyDispose = false;        private XmlDocument xmlDoc = new XmlDocument();          private string _xmlPath;        #region 构造与释构        public XMLoperate()        {        }        public XMLoperate(string xmlPath)        {            _xmlPath = xmlPath;        }        ~XMLoperate()        {            Dispose();        }        protected virtual void Dispose(bool isDisposing)        {            if (_alreadyDispose) return;            if (isDisposing)            {                //            }            _alreadyDispose = true;        }        #endregion        #region IDisposable 成员        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        #endregion        #region 根据父节点属性值读取子节点值        /// <summary>        /// 根据父节点属性读取字节点值        /// </summary>        /// <param name="XmlPath">xml路径</param>        /// <param name="FatherElenetName">父节点名</param>        /// <param name="AttributeName">属性值</param>        /// <param name="AttributeIndex">属性索引</param>        /// <param name="ArrayLength">要返回的节点数组长度</param>        /// <returns></returns>        public static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElenetName, string AttributeName, int AttributeIndex, int ArrayLength)        {            System.Collections.ArrayList al = new System.Collections.ArrayList();            XmlDocument docXml = new XmlDocument();            docXml.Load(@XmlPath);            XmlNodeList xn = docXml.DocumentElement.ChildNodes;            //遍历第一层节点            foreach (XmlElement element in xn)            {                //判断父节点是否为指定节点                if (element.Name == FatherElenetName)                {                    //判断父节点属性的索引是否大于指定索引                    if (element.Attributes.Count < AttributeIndex)                        return null;                    //判断父节点的属性值是否等于指定属性                    if (element.Attributes[AttributeIndex].Value == AttributeName)                    {                        XmlNodeList xx = element.ChildNodes;                        if (xx.Count > 0)                        {                            for (int i = 0; i < ArrayLength & i < xx.Count; i++)                            {                                al.Add(xx[i].InnerText);                            }                        }                    }                }            }            return al;        }        #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 static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElement, string AttributeName, string AttributeValue, int ArrayLength)        {            System.Collections.ArrayList al = new System.Collections.ArrayList();            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;        }        #endregion        #region 根据父节点属性值读取子节点值        /// <summary>        /// 根据父节点属性读取字节点值        /// </summary>        /// <param name="XmlPath">xml路径</param>        /// <returns></returns>        public static Dictionary<string, object> GetXMLAllInfo(string XmlPath)        {            if (XmlPath == "")            {                return null;            }            Dictionary<string, object> suggestions = new Dictionary<string, object>();            XmlDocument docXml = new XmlDocument();            docXml.Load(@XmlPath);            XmlNodeList xn = docXml.DocumentElement.ChildNodes;            //遍历第一层节点            foreach (XmlElement element in xn)            {                string name = element.Name;                if ("Collection"!= name)                {                    int attributes = element.Attributes.Count;                    Dictionary<string, object> obj = new Dictionary<string, object>();                    string key = "";                    foreach (System.Xml.XmlAttribute item in element.Attributes)                    {                        if (item.Name == "RegName")                        {                            key = item.Value;                        }                        else                        {                            obj.Add(item.Name, item.Value);                        }                    }                    if (element.ChildNodes.Count > 0)                    {                        Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);                        if (childList.Count > 0)                        {                            obj.Add("Members", childList);                        }                    }                    suggestions.Add(key, obj);                }                           }            return suggestions;        }        private static Dictionary<string, object> GetChildInfo(XmlNodeList childs)        {            Dictionary<string, object> child = new Dictionary<string, object>();            foreach (XmlElement element in childs)            {                if (element.Name != "Member")                    continue;                int attributes = element.Attributes.Count;                Dictionary<string, object> obj = new Dictionary<string, object>();                string key = "";                foreach (System.Xml.XmlAttribute item in element.Attributes)                {                    if (item.Name == "RegName")                    {                        key = item.Value;                    }                    else                    {                        obj.Add(item.Name, item.Value);                    }                }                if (element.ChildNodes.Count > 0)                {                                        Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);                    if (childList.Count > 0)                    {                        obj.Add("Members", childList);                    }                }                child.Add(key, obj);            }            return child;        }        #endregion        public static List<string> GetMember(string XmlPath, string tem)        {            if (XmlPath == "")            {                return null;            }            XmlDocument docXml = new XmlDocument();            docXml.Load(@XmlPath);            XmlNodeList xn = docXml.DocumentElement.ChildNodes[0].ChildNodes;            List<string> elem = new List<string>();            //遍历第一层节点            foreach (XmlElement element in xn)            {                foreach (System.Xml.XmlAttribute item in element.Attributes)                {                    if (item.Name == "TemplateName" && item.Value == tem)                    {                        elem.Add(element.ChildNodes[0].ChildNodes[0].Attributes["ElementName"].Value);                        elem.Add(element.ChildNodes[0].ChildNodes[1].Attributes["ElementName"].Value);                        elem.Add(element.ChildNodes[0].ChildNodes[2].Attributes["ElementName"].Value);                        return elem;                    }                }            }            return elem;        }        /// <summary>        /// 修改xml        /// </summary>        /// <param name="FilePath">文件地址</param>        /// <param name="RegName">节点名称</param>        /// <param name="Name">节点属性名称</param>        /// <param name="Value">节点属性值</param>        public static bool EditXmlInfo(string FilePath, string TagName, string Name, string Value)        {            try            {                XmlDocument xmlDoc = new XmlDocument();                xmlDoc.Load(FilePath);    //加载Xml文件                  XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);                foreach (XmlNode node in nodeList)                {                    XmlElement ele = (XmlElement)node;                    ele.SetAttribute(Name, Value);                }                xmlDoc.Save(FilePath);                return true;            }            catch /*(Exception e)*/            {                return false;            }        }        public static bool EditMemberXmlInfo(string FilePath, string TagName, string Name, string Value)        {            try            {                XmlDocument xmlDoc = new XmlDocument();                xmlDoc.Load(FilePath);    //加载Xml文件                  XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Member");                foreach (XmlNode node in nodeList)                {                    XmlElement ele = (XmlElement)node;                    if (ele.GetAttribute("RegName") == TagName)                    {                        ele.SetAttribute(Name, Value);                    }                                   }                xmlDoc.Save(FilePath);                return true;            }            catch /*(Exception e)*/            {                return false;            }        }        /// <summary>        /// 获取XML节点参数        /// </summary>        /// <param name="Name">节点参数名称</param>        /// <returns>节点参数</returns>        public static string GetXMLInformations(string xmlFilePath, string Name)        {            try            {                string value = string.Empty;                XmlDocument doc = new XmlDocument();                doc.Load(xmlFilePath);    //加载Xml文件                  XmlElement root = doc.DocumentElement;   //获取根节点                  XmlNodeList mainNodes = root.GetElementsByTagName("parameter"); //获取子节点集合                  foreach (XmlNode node in mainNodes)                {                    //获取Name属性值                    string name = ((XmlElement)node).GetAttribute("Name");                    if (name.Equals(Name))                    {                        value = ((XmlElement)node).GetAttribute("Value");                    }                }                return value;            }            catch (Exception)            {                return "";            }        }        /// <summary>        /// 修改第二层节点数据        /// </summary>        /// <param name="XmlPath">XML路径</param>        /// <param name="AttributeName">所有需要修改的属性名称</param>        /// <param name="Value">需要修改的值</param>        /// <returns></returns>        public static bool UpdateByAttribute(string XmlPath, string[] AttributeName, string[] Value)        {            try            {                XmlDocument docXml = new XmlDocument();                docXml.Load(@XmlPath);                XmlNodeList xn = docXml.DocumentElement.ChildNodes;                //遍历第一层节点                foreach (XmlElement element in xn)                {                    if (element.Attributes[0].Value == Value[0])                    {                        for (int i = 0; i < element.Attributes.Count; i++)                        {                            for (int j = 0; j < AttributeName.Count(); j++)                            {                                //判断父节点的属性值是否等于指定属性                                if (element.Attributes[i].Name == AttributeName[j])                                {                                    element.SetAttribute(AttributeName[j], Value[j]);                                    break;                                }                            }                        }                        break;                    }                }                docXml.Save(@XmlPath);                return true;            }            catch /*(Exception e)*/            {                return false;            }        }        public static int InsertAttribute(string XmlPath, string[] AttributeName, string[] Value, string nodeName)        {            try            {                XmlDocument docXml = new XmlDocument();                docXml.Load(@XmlPath);                XmlNodeList xn = docXml.DocumentElement.ChildNodes;                foreach (XmlElement element in xn)                {                    if (element.Attributes[0].Value == Value[0])                    {                        return -1;                    }                }                XmlElement xe = docXml.CreateElement(nodeName);                for (int i = 0; i < AttributeName.Count(); i++)                {                    xe.SetAttribute(AttributeName[i], Value[i]);                }                docXml.DocumentElement.AppendChild(xe);                docXml.Save(@XmlPath);                return 1;            }            catch /*(Exception e)*/            {                return 0;            }        }        public static int DeleteByAttribute(string XmlPath, string AttributeName, string Value)        {            try            {                XmlDocument docXml = new XmlDocument();                docXml.Load(@XmlPath);                XmlNodeList xn = docXml.DocumentElement.ChildNodes;                foreach (XmlElement element in xn)                {                    if (element.Attributes[AttributeName].Value == Value)                    {                        element.ParentNode.RemoveChild(element);                        docXml.Save(@XmlPath);                        return 1;                    }                }                return 2;            }            catch /*(Exception e)*/            {                return 0;            }        }        #region 报告模板        /// <summary>        /// 写入配置,也可以用来修改        /// </summary>        /// <param name="value">写入的值</param>        /// <param name="nodes">节点</param>        public void Write(string value, params string[] nodes)        {            //初始化xml            XmlDocument xmlDoc = new XmlDocument();            if (File.Exists(_xmlPath))                xmlDoc.Load(_xmlPath);            else                xmlDoc.LoadXml("<XmlConfig />");            XmlNode xmlRoot = xmlDoc.ChildNodes[0];            //新增、编辑 节点            string xpath = string.Join("/", nodes);            XmlNode node = xmlDoc.SelectSingleNode(xpath);            if (node == null)    //新增节点            {                node = makeXPath(xmlDoc, xmlRoot, xpath);            }            node.InnerText = value;            //保存            xmlDoc.Save(_xmlPath);        }        /// <summary>        /// 设置节点上属性的值        /// </summary>        /// <param name="AttributeName">属性名</param>        /// <param name="AttributeValue">属性值</param>        /// <param name="nodes">选择节点</param>        public void SetAttribute(string AttributeName, string AttributeValue, params string[] nodes)        {            //初始化xml            XmlDocument xmlDoc = new XmlDocument();            if (File.Exists(_xmlPath))                xmlDoc.Load(_xmlPath);            else                xmlDoc.LoadXml("<XmlConfig />");            XmlNode xmlRoot = xmlDoc.ChildNodes[0];            //新增、编辑 节点            string xpath = string.Join("/", nodes);            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);            if (element == null)    //新增节点            {                element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);            }            //设置节点上属性的值            element.SetAttribute(AttributeName, AttributeValue);            //保存            xmlDoc.Save(_xmlPath);        }        public string GetAttribute(string AttributeName, params string[] nodes)        {            //初始化xml            XmlDocument xmlDoc = new XmlDocument();            if (File.Exists(_xmlPath))                xmlDoc.Load(_xmlPath);            else                xmlDoc.LoadXml("<XmlConfig />");            XmlNode xmlRoot = xmlDoc.ChildNodes[0];            //新增、编辑 节点            string xpath = string.Join("/", nodes);            XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);            if (element == null)    //新增节点            {                element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);            }            //设置节点上属性的值            string retstr = element.GetAttribute(AttributeName);            //保存            xmlDoc.Save(_xmlPath);            return retstr;        }        /// <summary>        /// 读取配置        /// </summary>        /// <param name="nodes">节点</param>        /// <returns></returns>        public string Read(params string[] nodes)        {            XmlDocument xmlDoc = new XmlDocument();            if (File.Exists(_xmlPath) == false)                return null;            else                xmlDoc.Load(_xmlPath);            string xpath = string.Join("/", nodes);            XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);            if (node == null)                return null;            return node.InnerText;        }        /// <summary>        /// 删除节点        /// </summary>        /// <param name="nodes"></param>        public void RemoveNode(params string[] nodes)        {            XmlDocument xmlDoc = new XmlDocument();            if (File.Exists(_xmlPath) == false)                return;            else                xmlDoc.Load(_xmlPath);            string xpath = string.Join("/", nodes);            XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);            //取得父节点            string[] father_nodes = new string[nodes.Count() - 1];            //对父节点进行初始化            for (int i = 0; i < nodes.Count() - 1; i++)            {                father_nodes[i] = (string)nodes[i].Clone();            }            string fast_xpath = string.Join("/", father_nodes);            XmlNode fastnode = xmlDoc.SelectSingleNode("/XmlConfig/" + fast_xpath);            if (node == null)                return;            if (fastnode == null)                return;            //使用父节点删除子节点            fastnode.RemoveChild(node);            //保存            xmlDoc.Save(_xmlPath);        }        //递归根据 xpath 的方式进行创建节点        static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)        {            // 在XPath抓住下一个节点的名称;父级如果是空的则返回            string[] partsOfXPath = xpath.Trim('/').Split('/');            string nextNodeInXPath = partsOfXPath.First();            if (string.IsNullOrEmpty(nextNodeInXPath))                return parent;            // 获取或从名称创建节点            XmlNode node = parent.SelectSingleNode(nextNodeInXPath);            if (node == null)                node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));            // 加入的阵列作为一个XPath表达式和递归余数            string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());            return makeXPath(doc, node, rest);        }        #endregion        #region 特殊颗粒XML处理        /// <summary>        /// 特殊颗粒XML读取        /// </summary>        /// <param name="FilePath">文件地址</param>        /// <param name="RegName">节点名称</param>        /// <returns>DataSet</returns>        public static DataSet GetXMLRegList(string FilePath, string TagName)        {            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.Load(FilePath);    //加载Xml文件              XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);            List<DataSet> dsList = new List<DataSet>();            DataSet dsResult = new DataSet();            foreach (XmlNode node in nodeList)            {                XmlElement ele = (XmlElement)node;                DataSet dsn = new DataSet();                StringReader read = new StringReader(node.OuterXml);                dsn.ReadXml(read);                dsList.Add(dsn);            }            for (int i = 0; i < dsList.Count; i++)            {                if (i == 0)                {                    dsResult = dsList[i];                }                else                {                    dsResult.Merge(dsList[i], false, MissingSchemaAction.Ignore);                }            }                       return dsResult;        }                     public static bool UpdateSpecialGrayXMLFile(string FilePath, DataGridView dg,bool isToRun)        {            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.Load(FilePath);    //加载Xml文件              xmlDoc.RemoveAll();            XmlElement xmlData = xmlDoc.CreateElement("XMLData");            xmlDoc.AppendChild(xmlData);            if (isToRun)            {                xmlData.SetAttribute("ToRun", "True");            }            else             {                xmlData.SetAttribute("ToRun", "False");            }            XmlElement membercol = xmlDoc.CreateElement("Collection");            membercol.SetAttribute("RegName", "GrayRangeList");            xmlData.AppendChild(membercol);            for (int i = 0; i < dg.Rows.Count; i++)            {                              XmlElement member = xmlDoc.CreateElement("Member");                membercol.AppendChild(member);                for (int j = 0; j < dg.Columns.Count; j++)                {                    //设置参数                    member.SetAttribute("RegName", dg.Rows[i].Cells["RegName"].Value.ToString());                    member.SetAttribute("start", dg.Rows[i].Cells["start"].Value.ToString());                    member.SetAttribute("end", dg.Rows[i].Cells["end"].Value.ToString());                    member.SetAttribute("diameterStart", dg.Rows[i].Cells["diameterStart"].Value.ToString());                    member.SetAttribute("diameterEnd", dg.Rows[i].Cells["diameterEnd"].Value.ToString());                    if (dg.Rows[i].Cells["collectXray"].Value==DBNull.Value || dg.Rows[i].Cells["collectXray"].Value.ToString() == "false")                    {                        member.SetAttribute("collectXray", "false");                    }                    else                     {                        member.SetAttribute("collectXray", "true");                    }                                                     }            }                      xmlDoc.Save(FilePath);            return true;        }               #endregion    }}
 |