2014-09-11 52 views
0

下面的函數查找文件,導航到指定的父節點,並遍歷子節點查找預定義的元素名稱。替代開關案例讀取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();   
    } 

回答

1

作爲替代當前的方法,您可以使用多個SelectSingleNode()就像這樣:

XmlNode xmlLst = xDoc.SelectSingleNode("parentnode/childnode"); 
_User = xmlLst.SelectSingleNode("user").InnerText; 
_Password = xmlLst.SelectSingleNode("password").InnerText; 
.... 

,或者您可以使用較新的XML API,XDocument嘗試一種完全不同的路線,而不是XmlDocument

XDocument xDoc = XDocument.Load(configfilepath); 
Xelement xmlLst = xDoc.Element("parentnode").Element("childnode"); 
_User = (string)xmlLst.Element("user"); 
_Password = (string)xmlLst.Element("password"); 
.... 
+0

感謝您將XDocument介紹給我,簡單得多,喜歡它! – PurpleSmurph 2014-09-11 09:37:07

0

而另一種替代方法是使用Dictionary<string, string>,如下所示:

string confPath = (fp + @"\config.xml"); 
XmlDocument xDoc = new XmlDocument(); 
xDoc.Load(configfilepath); 
XmlNode xmlLst = xDoc.SelectSingleNode("parentnode/childnode"); 
var nodeDict = xmlLst.ChildNodes.OfType<XmlNode>() 
       .ToDictionary(nodeKey => nodeKey.Name, nodeVal => nodeVal.InnerText); 

現在它的時間來訪問該值。

var _User = nodeDict["user"]; 
// OR 
Console.WriteLine(nodeDict["user"] + " " + nodeDict["password"] + " " + nodeDict["serverip"]); 
//...... so on........