测试程序功能为读取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();
}
}
}
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");
}
}
}