很多时候,我们在编写软件的时候,都需要在软件外部对其进行配置。利用本文所述技巧,可以实现在外部XML文件中读取软件进行配置,下面不说废话,直接贴出XML和相应解析代码:
XML文件
<System>
<Server>
<ServerIP>192.168.1.252</ServerIP>
<ServerPort>8080</ServerPort>
<ServerUrl>/xxxx</ServerUrl>
</Server>
<RealSize>
<XLength>2000</XLength>
<YLength>2000</YLength>
</RealSize>
<Coord>
<Mode>2</Mode>
</Coord>
</System>
相应脚本
using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
public class ParseXML : MonoBehaviour{
private string serverIP;
private string serverPort;
private string serverUrl;
//实际定位范围
private string xLength;
private string yLength;
//坐标系模式
private string mode;
// Use this for initialization
void Start(){
string configPath = Application.dataPath;
int num = configPath.LastIndexOf ("/");
configPath = configPath.Substring (0,num);
string url = configPath + "/config/systemconfig.xml";
/**
* 开始解析XML文件
*/
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load (url);
if(xmlDoc.HasChildNodes){
/**
* 获取服务器信息
*/
XmlNodeList nodeList=xmlDoc.GetElementsByTagName("Server");
foreach (XmlNode node in nodeList){
serverIP=node.SelectSingleNode("ServerIP").InnerText;
serverPort=node.SelectSingleNode("ServerPort").InnerText;
serverUrl=node.SelectSingleNode("ServerUrl").InnerText;
}
nodeList=xmlDoc.GetElementsByTagName("RealSize");
foreach (XmlNode node in nodeList){
xLength=node.SelectSingleNode("XLength").InnerText;
yLength=node.SelectSingleNode("YLength").InnerText;
}
nodeList=xmlDoc.GetElementsByTagName("Coord");
foreach (XmlNode node in nodeList){
mode=node.SelectSingleNode("Mode").InnerText;
}
}
}
public string getServerIP(){
return serverIP;
}
public string getServerPort(){
return serverPort;
}
public string getServerUrl(){
return serverUrl;
}
public string getXLength(){
return xLength;
}
public string getYLength(){
return yLength;
}
public string getMode(){
return mode;
}
}