1. 程式人生 > >XMLHelper類, 實現對節點屬性的讀取和修改

XMLHelper類, 實現對節點屬性的讀取和修改

測試程式功能為讀取XML檔案中Server結點的IP和Port屬性

建立的是c#控制檯程式

0. XMLFile


1. Solution


2. XMLHelper.cs

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

namespace ServerInfoXMLHelper
{
    class XMLHelper
    {
        XDocument document = null;
        public string fileName { get; set; }
        public string AttributeValue { get; set; }

        public XMLHelper(string fileName)
        {
            if (!File.Exists(fileName))
                Console.WriteLine(fileName + "does not exists.");

            this.fileName = fileName;
        }

        public void OpenXMLFile()
        {
            try
            {
                document = XDocument.Load(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CloseXMLFile()
        {
            try
            {
                document.Save(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetAttributeValue(string elementName, string AttributeName)
        {
            OpenXMLFile();

            try
            {
                XElement root = document.Root;
                XElement element = root.Element(elementName);
                this.AttributeValue = element.Attribute(AttributeName).Value;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            CloseXMLFile();

            return this.AttributeValue;
        }

        public void SetAttributeValue(string elementName, string AttributeName, string AttributeValue)
        {
            OpenXMLFile();

            try
            {
                XElement root = document.Root;
                XElement element = root.Element(elementName);
                element.SetAttributeValue(AttributeName, AttributeValue);
                root.Save(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            CloseXMLFile();
        }
    }
}
3. Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServerInfoXMLHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadXMLTest();
            WriteXMLTest();
        }

        static void ReadXMLTest()
        {
            XMLHelper xmlHelper = new XMLHelper("ServerInfo.xml");
            string ServerIP = xmlHelper.GetAttributeValue("UVSSServer", "IP");
            string ServerPort = xmlHelper.GetAttributeValue("UVSSServer", "port");
        }

        static void WriteXMLTest()
        {
            XMLHelper xmlHelper = new XMLHelper("ServerInfo.xml");
            xmlHelper.SetAttributeValue("Server", "port", "20146");
        }

    }
}