xml增、删、查、改

 #region xml操作

        /// <summary>
        /// 读取xml数据到dataset
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static DataTable  ReadXmlToDataTable(string filepath)
        {
            DataTable dt = new DataTable();
            if (!System.IO.File.Exists(filepath))
            {
                return dt;
            }
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNodeList xnl = xmlDoc.SelectSingleNode("//NewDataSet").ChildNodes;
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("link");
            dt.Columns.Add("title");
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.Name == "BbsItem")
                {
                    DataRow _row = dt.NewRow();
                    _row["id"] = xe.GetAttribute("id");
                    _row["title"] = xe["title"].InnerText;
                    _row["link"] = xe["link"].InnerText;
                    dt.Rows.Add(_row);
                }
            }
            DataView dv = dt.DefaultView;
            dv.Sort = "id";
            return dv.ToTable() ;
        }

        /// <summary>
        /// 读取最大ID
        /// </summary>
        public static int GetMaxIdByTypeid(string xmlpath)
        {
            if (!System.IO.File.Exists(xmlpath))
            {
                return 0;
            }
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlpath);
            XmlNode root = xmlDoc.SelectSingleNode("//NewDataSet"); //查找<NewDataSet>
            XmlElement xe = (XmlElement)root;
            return Convert.ToInt32(xe.GetAttribute("maxid").ToString());
        }

        /// <summary>
        /// 增加节点后更新最大节点标记MaxId
        /// </summary>
        /// <param name="xmlpath"></param>
        /// <remarks></remarks>
        public static void EditMaxIdByTypeid(string xmlpath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlpath);
            XmlNode root = xmlDoc.SelectSingleNode("//NewDataSet"); //查找<NewDataSet>
            XmlElement xe = (XmlElement)root;
            xe.SetAttribute("id", (Convert.ToInt32(xe.GetAttribute("maxid").ToString()) + 1).ToString());
        }

        /// <summary>
        /// 插入xml新节点,并更新最大节点标记MaxId
        /// </summary>
        public static void InsertXmlNode(string xmlpath, int id, string link, string title)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlpath);
            XmlNode root = xmlDoc.SelectSingleNode("//NewDataSet"); //查找<NewDataSet>
            XmlElement xe = (XmlElement)root;
            xe.SetAttribute("maxid", id.ToString());

            XmlElement xe1 = xmlDoc.CreateElement("BbsItem"); //创建一个<BbsItem>节点
            xe1.SetAttribute("id", id.ToString()); //设置该节点id属性

            XmlElement xesub1 = xmlDoc.CreateElement("link");
            XmlCDataSection xcs = xmlDoc.CreateCDataSection("link");
            xcs.InnerText = link; //设置link节点
            xesub1.AppendChild(xcs);
            xe1.AppendChild(xesub1); //添加到<BbsItem>节点中

            XmlElement xesub2 = xmlDoc.CreateElement("title");
            xesub2.InnerText = title;
            xe1.AppendChild(xesub2);

            root.AppendChild(xe1); //添加到<DataNode>节点中
            xmlDoc.Save(xmlpath);
        }

        /// <summary>
        /// 修改xml节点值
        /// </summary>
        /// <remarks></remarks>
        public static void UpdateXmlNode(string filepath, int id, string url, string title)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(filepath);
            XmlNode node = doc.SelectSingleNode("//NewDataSet/BbsItem[@id=\'" + id.ToString() + "\']");
            XmlNodeList xnl = node.ChildNodes;
            foreach (XmlNode xn in xnl)
            {

                XmlElement xe = (XmlElement)xn;
                if ((string)xe.Name == "link")
                {
                    XmlCDataSection xcs = (XmlCDataSection)(xe.ChildNodes[0]);
                    xcs.Data = url;
                }
                else if ((string)xe.Name == "title")
                {
                    xe.InnerXml = title;
                }
                else
                {
                }
            }
            doc.Save(filepath);
        }

        /// <summary>
        /// 删除节点
        /// </summary>
        public static void DeleteXmlNode(string xmlpath, int id)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlpath);
            XmlNodeList xnl = xmlDoc.SelectSingleNode("//NewDataSet").ChildNodes;

            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.Name == "BbsItem" && xe.GetAttribute("id") == id.ToString())
                {
                  
                    xe.ParentNode.RemoveChild(xe); //删除该节点的全部内容
                }
            }
            xmlDoc.Save(xmlpath);
        }

        /// <summary>
        /// 更换xml id(修改顺序时)
        /// </summary>
        /// <remarks></remarks>
        public static void ChangeXmlId(string filepath, int id1, int id2)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(filepath);
            XmlNode node1 = doc.SelectSingleNode("//NewDataSet/BbsItem[@id=\'" + id1.ToString() + "\']");
            XmlElement xe1 = (XmlElement)node1;
            XmlNode node2 = doc.SelectSingleNode("//NewDataSet/BbsItem[@id=\'" + id2.ToString() + "\']");
            XmlElement xe2 = (XmlElement)node2;
            xe1.SetAttribute("id", id2.ToString());
            xe2.SetAttribute("id", id1.ToString());
            doc.Save(filepath);
        }

        #endregion



        /// <summary>
        /// 写入数据到文件
        /// </summary>
        /// <remarks></remarks>
        public void StreamWrite(string filePath, string strContent)
        {
            if (filePath.Length > 0)
            {
                StreamWriter sw = null;
                if (!Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                }

                try
                {
                    sw = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
                    sw.Write(strContent);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
                finally
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }

 写xml,改进写法,当文件不存在时,先新建文件

  /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteErrorLog(Exception ex)
        {
           
            DataTable dt = new DataTable("ErrorLog");
            dt.Columns.Add("Date");
            dt.Columns.Add("Message");
            DataRow dr = dt.NewRow();
            dr["Date"] = DateTime.Now;
            dr["Message"] = ex.Message;
            dt.Rows.Add(dr);
            string path = Config.GetConfigValue("BASE_ERROR_FOLDER");//路径
            //目录是否存在
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fullPath = path + "errorLog.xml";
            //文件是否存在
            if (!File.Exists(fullPath))
            {
                dt.WriteXml(fullPath, XmlWriteMode.WriteSchema);
               
            }
            else {
                AppandXml(ex, fullPath);//存在,则追加
            }
           
        }
        /// <summary>
        /// 追加写入XML文件
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="fullPath">文件全路径</param>
        public static void AppandXml(Exception ex, string fullPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fullPath);
            XmlNode root = xmlDoc.SelectSingleNode("NewDataSet");//查找到根目录
            XmlElement errorLog_ele = xmlDoc.CreateElement("ErrorLog");

            XmlElement date_ele = xmlDoc.CreateElement("Date");
            date_ele.InnerText = DateTime.Now.ToString();
            errorLog_ele.AppendChild(date_ele);

            XmlElement message_ele = xmlDoc.CreateElement("Message");
            message_ele.InnerText =ex.Message;
            errorLog_ele.AppendChild(message_ele);

            root.AppendChild(errorLog_ele);
            xmlDoc.Save(fullPath);
        }

 

posted @ 2014-10-31 14:13  nik2011  阅读(152)  评论(0)    收藏  举报