一个简单的c#操作XML文件的类,只能操作一层的节点

using System;

using System.Xml;

 

namespace WindowsFormsApplication3

{

    class XMLControl

    {

        XmlDocument xmldoc; //xml文件对象

        XmlElement xmlelement;  //xml元素

        XmlText xmltext;  //xml文本

        XmlNodeList xmllist;//xml列表

        string sUrl="\\DBset.xml";

        public XMLControl()

        {

            xmldoc = new XmlDocument();

            xmldoc.Load("\\DBset.xml");

        }

        public XMLControl(string sxmlurl) //xmlurl是XML文件的路径

 

没有删除的方法

        {

            xmldoc = new XmlDocument();

            xmldoc.Load(sxmlurl);

            sUrl = sxmlurl;

        }

        public bool AddNode(string sNodeName , string sNodeValue) //增加一个节点

        {

            try

            {

                xmlelement = xmldoc.CreateElement(sNodeName);

                xmltext = xmldoc.CreateTextNode(sNodeValue);

                xmlelement.AppendChild(xmltext);

                xmldoc.ChildNodes.Item(1).AppendChild(xmlelement);

                xmldoc.Save(sUrl);

                return true;

            }

            catch

            {

                return false;

            }

        }

        public bool UpdataNodeValue(string sNodeName,string sNodeValue)

        {

            try

            {

                xmllist = xmldoc.GetElementsByTagName(sNodeName);

                xmllist[0].InnerText = sNodeName;

                xmldoc.Save(sUrl);

                return true;

            }

            catch

            {

                return false;

            }

        }

        public string SelectNode(string sNodeName)

        {

            string sNodeValue=null;

            try

            {

                xmllist = xmldoc.SelectNodes("//setting/" + sNodeName);

                foreach(XmlNode xl in xmllist)

                {

                    sNodeValue = xl.InnerText.ToString();

                }

                return sNodeValue;

            }

            catch

            {

                return null;

            }

        }

    }

}

 

posted @ 2010-03-12 09:43  爱如少年  阅读(285)  评论(0编辑  收藏  举报