2011-08-23 100 views
1

XML:捕捉特定元素

<?xml version="1.0" encoding="utf-8" ?> 
<StudentList> 
<student> 
    <name>Ram</name> 
    <Id>1</Id> 
</student> 

    <student> 
    <name>Hari</name> 
    <Id>2</Id> 
</student> 
    <student> 
    <name>Gita</name> 
    <Id>3</Id> 
    </student> 
    <student> 
    <name>Sita</name> 
    <Id>4</Id> 
    </student> 
</StudentList> 

在頁面加載:

XmlDocument XD = new XmlDocument(); 
     XD.Load(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml")); 
     XmlNodeList nodeListName = XD.GetElementsByTagName("student"); 
     foreach (XmlNode xNode in nodeListName) 
     { 
      foreach (XmlElement xelement in xNode) 
      { 
       PlaceHolder pshd = new PlaceHolder(); 
       LblDisplay.Text += xelement.FirstChild.Value + " "; 
       string Name += xelement.FirstChild.Value; 
      } 
      LblDisplay.Text += "<br/>"; 

     } 

我要趕僅從上述XML文件名,但我得到的名稱和ID both.How能我這樣做plz幫助。

回答

2
XmlDocument xml = new XmlDocument(); 
xml.LoadXml(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml")); 

XmlNodeList xnList = xml.SelectNodes("/StudentList/student"); 
foreach (XmlNode xn in xnList) 
{ 
    string name= xn["name"].InnerText; 
    string Id= xn["Id"].InnerText; 
} 
+0

非常感謝我究竟得到了什麼,我再次want.Thanks。 –

+0

查找有關XPath的更多信息 – Rumplin

1

相反迭代xNode的你只是想它的FirstChild

foreach (XmlNode xNode in nodeListName) 
{ 
    string name = xNode.FirstChild.InnerText; 
    LblDisplay.Text += name + "<br/>"; 
} 
+0

感謝你我很棒我得到了我想要的東西。但是plz幫助一點點more.If我想只抓住'id'呢? –

0

您可以使用XPath一路:

nodeList = XD.SelectNodes("//student/name") 
foreach (XMlNode node in nodeList){ 
    LblDisplay.Text += node.Value + "<br/>"; 
} 
1

您還可以使用LINQ到XML(在System.Xml.Linq的命名空間),使用的XDocument:

XDocument xDoc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("XmlFile.xml")); 

var names = from x in xDoc.Descendants("student") 
      select x.Element("name"); 

foreach (XElement studentName in names) 
{ 
    LblDisplay.Text += studentName.Value + " "; 
} 

LblDisplay.Text += "<br />"; 

如果你想在ID而不是,你可以在select x.Element("name");線代替「ID」。

或者,你可以抓住這兩個名稱和ID,並返回它們作爲匿名類型的集合:

var students = from x in xDoc.Descendants("student") 
       select new 
        { 
         name = x.Element("name").Value, 
         id = x.Element("Id").Value 
        }; 

然後你可以訪問正是如此:

foreach (var student in students) 
{ 
    LblDisplay.Text += student.name + " student.Id + " "; 
} 

或任何你想做的事用它。

0
String fileName = @"C:\Documents and Settings\aritra.ghosh\Desktop\Student.xml"; 
     XmlDocument xDoc = new XmlDocument(); 
     xDoc.Load(fileName); 
     XmlNodeList list = xDoc.SelectNodes("StudentList/student/name"); 
     foreach (XmlNode item in list) 
     { 
      Console.WriteLine(item.InnerText); 
     }