本文主要介紹了c#讀取XML多級子節點的方法。具有很好的參考價值。下面跟著小編一起來看下吧
話不多說,請看代碼:
string xmlFilePath = "D:\\log_xml\\MarInfo.xml"; //Server.MapPath(@"相對路徑如/xml/test.xml");XmlDocument doc = new XmlDocument();doc.Load(xmlFilePath);//載入XML檔案string rst = "";//使用xpath運算式選擇文檔中所有的student子節點XmlNodeList studentNodeList = doc.SelectNodes("Root/MarketList/Market");if (studentNodeList != null){foreach (XmlNode studentNode in studentNodeList){//通過Attributes獲得屬性名稱字為name的屬性string name = studentNode.Attributes["MarketName"].Value+":";rst+= name;//通過SelectSingleNode方法獲得當前節點下的SubMarketList子節點XmlNode coursesNode = studentNode.SelectSingleNode("SubMarketList");//通過ChildNodes屬性獲得courseNode的所有一級子節點XmlNodeList courseNodeList = coursesNode.ChildNodes;if (courseNodeList != null){foreach (XmlNode courseNode in courseNodeList){rst += courseNode.Attributes["Name"].Value+",";}rst += "<br/>";}}}Response.Write(rst);