最近做项目又遇到一个需要写配置文件的,懒得自己写就把之前写的一个简单的扒出来改了改,在此贴出来,省得以后还要重新写
代码:
private string appSettingName = "Settings.xml"; private void InitSetting() { string path = Path.Combine(Application.streamingAssetsPath, appSettingName); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); XmlNodeList nodeList = xmlDoc.SelectSingleNode("appSettings").ChildNodes; foreach (XmlNode temp in nodeList) { if(temp is XmlComment) { continue; } XmlElement xml = (XmlElement)temp; string key = xml.GetAttribute("key"); if(key== "sensorPara") { float f; int i; sensorPara.sensorHeight = float.TryParse(xml.GetAttribute("sensorHeight"), out f) ? f : 1f; sensorPara.sensorAngle = float.TryParse(xml.GetAttribute("sensorAngle"), out f) ? f : 0f; sensorPara.minDistance = float.TryParse(xml.GetAttribute("minDistance"), out f) ? f : 0.5f; sensorPara.maxDistance = float.TryParse(xml.GetAttribute("maxDistance"), out f) ? f : 3.5f; sensorPara.maxLRDistance = float.TryParse(xml.GetAttribute("maxLRDistance"), out f) ? f : 1f; sensorPara.trackedUsers = int.TryParse(xml.GetAttribute("trackedUsers"), out i) ? i : 1; continue; } string value = xml.GetAttribute("value"); appParaKeys.Add(key); appParaValues.Add(value); } float t; time = float.TryParse(appParaValues[0], out t) ? t : 2f; }
配置文件:
<?xml version="1.0" encoding="utf-8"?> <appSettings> <!--app_cursorTime时间--> <add key="app1_cursorTime" value="1.5"/> <!--app_web网址--> <add key="app2_web" value="https://www.baidu.com"/> <!--app_exe应用程序--> <add key="app3_video" value="D: estVideo est.mp4"/> <!--sensorPara传感器参数--> <add key="sensorPara" sensorHeight="2.2" sensorAngle="-15" minDistance="1" maxDistance="2" maxLRDistance="0.5" trackedUsers="1"/> </appSettings>