【发布时间】:2015-03-30 13:49:07
【问题描述】:
我有一个班级学生,我想读取一个包含学生信息的 xml 文件并将信息放入列表中。 我的代码:
internal class Student
{
private string name = null;
private string age = null;
private string age = null;
public string Name
{
get { return name; }
set { name = value; }
}
public string Age
{
get { return age; }
set { age = value; }
}
}
我正在阅读以下 xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<STUDENT_INFO>
<STUDENT>
<NAME>Name_1</NAME>
<AGE>1</AGE>
</STUDENT>
<STUDENT>
<NAME>Name_2</NAME>
<AGE>2</AGE>
</STUDENT>
<STUDENT>
<NAME>Name_3</NAME>
<AGE>3</AGE>
</STUDENT>
</STUDENT_INFO>
这是我的主要方法:
string filePath = "C:\\StudentInfo.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
StreamReader reader = new StreamReader(filePath);
string line = "";
string xmlValue = null;
Student stu = new Student();
List<Student> stuList = new List<Student>();
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("<NAME>"))
{
XmlNodeList elemList = doc.GetElementsByTagName("NAME");
for (int i = 0; i < elemList.Count; i++)
{
xmlValue = elemList[i].InnerXml;
stu.Name = xmlValue;
Console.WriteLine(xmlValue);
}
}
stuList.add(stu);
}
我需要读取 xml 并将 stu 对象放入 stuList。 我该怎么做?
更新:我使用了提到我的 Pradip Nadar 的 LINQ 语句
XDocument xdoc = XDocument.Load("C:\\StudentInfo.xml");
List<Student> lv1s = (from lv1 in xdoc.Descendants("STUDENT")
select new Student
{
Name = lv1.Element("NAME").Value,
Age = lv1.Element("AGE").Value
}).ToList();
foreach (Student s in lv1s)
{
Console.WriteLine(s.Name);
Console.WriteLine(s.Age);
}
【问题讨论】:
-
这里面用XMLSerializer可以吗?
-
StreamReader不用于解析 XML 文件,它用于普通(非结构化)文本文件。使用XmlDocument/XPath,或XDocument,或XML 序列化程序。 -
XPathDocument doc = new XPathDocument(filePath); XPathNavigator 导航 = doc.CreateNavigator(); XPathExpression 表达式; expr = nav.Compile("/STUDENT_INFO/STUDENT/NAME"); XPathNodeIterator 迭代器 = nav.Select(expr); while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); Console.WriteLine("名称" + nav2.Value); @kennyzx 上面的代码有效。但是我该如何填写列表呢??
-
将新创建的学生实例添加到列表中。 while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone();
stuList.Add(new Student(){ Name = nav2.Value };);