1. 程式人生 > >asp.net簡單讀取xml檔案資訊

asp.net簡單讀取xml檔案資訊

            //以下是迴圈讀取xml檔案中節點的值
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(Server.MapPath("Student1.xml")); //載入xml
                XmlNodeList NodeList = xmlDoc.SelectNodes("/Students/Student"); //xml節點的路徑
                //迴圈遍歷節點
                for (int i = 0; i < NodeList.Count; i++)
                {
                    string xmlStuName = NodeList[i].ChildNodes[0].InnerText;    //獲取第一個Student節點的StuName
                    string xmlStuSex = NodeList[i].ChildNodes[1].InnerText;     //獲取第一個Student節點的StuSex
                    string xmlStuAge = NodeList[i].ChildNodes[2].InnerText;     //獲取第一個Student節點的StuAge
                    string xmlStuAddress = NodeList[i].ChildNodes[3].InnerText; //獲取第一個Student節點的StuAddress
                    //迴圈讀取xml節點資訊
                    Response.Write("當前的xml檔案中的節點StuName是:" + xmlStuName + "<br />" + "當前的xml檔案中的節點StuSex是:" + xmlStuSex + "<br />" + "當前的xml檔案中的節點StuAge是:" + xmlStuAge + "<br />" + "當前的xml檔案中的節點StuAddress是:" + xmlStuAddress);
                }

//Student1.xml檔案

<?xml version="1.0" encoding="utf-8"?>
<Students>
  <Student>
    <StuName id=1 name='lizong'>李總</StuName>
    <StuSex>男</StuSex>
    <StuAge>24</StuAge>
    <StuAddress>深圳寶安</StuAddress>
  </Student>
</Students>


 //一下這個是讀取xml檔案裡面節點的屬性

      XmlDocument doc = new XmlDocument();
         doc.Load(Server.MapPath("Student1.xml")); 
	String d1 = doc.SelectSingleNode("//StuName[@id='1']/@name").Value;//讀取stuname標籤裡面的id為1的name的值
 
         XmlNodeList list = doc.GetElementsByTagName("StuName"); //Student1.xml檔案裡面的StuName節點
         foreach (XmlElement host in list)  
         {

              
            Response.Write("Student1.xml節點裡面的StuName節點的name屬性的值為:"+host.Attributes["name"].Value+"<br/>");     
            Response.Write("Student1.xml節點裡面的StuName節點的id屬性的值為:"+host.Attributes["id"].Value + "<br/>");
  
          }