从XML文件中捕获特定元素

时间:2011-08-23 06:53:12

标签: c# asp.net xml

的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两个。我怎么做才能帮助。

5 个答案:

答案 0 :(得分: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;   
}

答案 1 :(得分:1)

而不是迭代xNode,而只需要FirstChild

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

答案 2 :(得分:1)

您还可以使用LINQ to 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 + " ";
}

或者你想用它做什么。

答案 3 :(得分:0)

您可以一直使用XPath:

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

答案 4 :(得分: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);
        }