下面的函數查找文件,導航到指定的父節點,並遍歷子節點查找預定義的元素名稱。替代開關案例讀取XML
我從一個XML文件中讀取並分配節點內部文本值,靜態字段,只希望挑選出某些節點,這不一定是爲了爲用戶將被允許編輯XML配置文件。
目前我不得不按照節點出現的順序來確定硬件代碼,因爲我不認爲這很重要 - 理想情況下我希望避免這種情況。
有沒有更好的選擇,或者有什麼我做錯了開關櫃?
我的代碼,因爲它代表:
public void ReadConfig()
{
string fp = _AppPath + @"\myfolder";
try
{
string confPath = (fp + @"\config.xml");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(configfilepath);
XmlNode xmlLst = xDoc.SelectSingleNode("parentnode/childnode");
foreach (XmlNode node in xmlLst.ChildNodes)
{
switch(node.Name)
{
case "user":
_User = node.InnerText;
break;
case "password":
_Password = node.InnerText;
break;
case "serverip":
_serverIP = node.InnerText;
break;
case "mailport":
_mailPort = int.Parse(node.InnerText);
break;
case "recipient":
_recipient = node.InnerText;
break;
default:
WriteErrorLog("Issue getting server details from XML config file.");
break;
}
}
}
完全可行的解決方案
感謝幫助,下面是工作的代碼。
public static void ReadFromXMLXDoc()
{
// XDocument xDocu;
string xmlFilePath = (@"somewhere\Config.xml");
XDocument xDocu = XDocument.Load(xmlFilePath);
XElement xmlList = xDocu.Element("configuration").Element("parent").Element("child");
_one = (string)xmlList.Element("option1");
_two = (string)xmlList.Element("option2");
_three = (string)xmlList.Element("option3");
Console.WriteLine(_one + " " + _two + " " + _three);
Console.ReadLine();
}
感謝您將XDocument介紹給我,簡單得多,喜歡它! – PurpleSmurph 2014-09-11 09:37:07