正在使用XmlDocument Nodelist读取XML文件
本文关键字:读取 XML 文件 Nodelist XmlDocument | 更新日期: 2023-09-27 18:26:17
有没有什么方法可以使用SelectSingleNode
而不必实际输入"math"、"physics"或"technologija",这样我就可以在任何输入的情况下阅读它?
到目前为止,读数是这样的:
XmlNodeList nodelist = xd.SelectNodes("/studentai/Evening");
foreach (XmlNode node in nodelist)
{
Student tc = new Student();
tc.id = node.Attributes.GetNamedItem("id").Value;
tc.name = node.Attributes.GetNamedItem("name").Value;
XmlNode n = node.SelectSingleNode("grades");
tc.grade1 = n.ChildNodes.Item(0).InnerText;
...
此外,由于有"晚上"answers"白天"的学生,我应该使用另一个nodelist/foreach(XmlNodeList nodelist = xd.SelectNodes("/students/Evening");
)来阅读它们,或者我可以以某种方式将/students/Evening
和students/Day
组合起来?
XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<students>
<Evening id="36453" name="Petras">
<grades>
<math>
<grade1>5</grade1>
<grade2>7</grade2>
</math>
<technologija>
<grade1>8</grade1>
<grade2>4</grade2>
</technologija>
</grades>
<average>6.00</average>
</Evening>
<Day id="75643" name="Jonas">
<grades>
<math>
<grade1>8</grade1>
<grade2>7</grade2>
</math>
<physics>
<grade1>7</grade1>
<grade2>10</grade2>
</physics>
</grades>
<average>8</average>
</Day>
<Day id="48843" name="Andrius">
<grades>
<math>
<grade1>5</grade1>
<grade2>5</grade2>
</math>
<physics>
<grade1>5</grade1>
<grade2>7</grade2>
</physics>
</grades>
<average>5.50</average>
</Day>
<Evening id="56442" name="Antanas">
<grades>
<math>
<grade1>8</grade1>
<grade2>8</grade2>
</math>
<technologija>
<grade1>8</grade1>
<grade2>10</grade2>
</technologija>
</grades>
<average>8.50</average>
</Evening>
</students>
不知道我的问题是不是太不清楚了,但我终于找到了正确的方法:
首先,为了获得模块1,我使用了tc.module1 = n.FirstChild.Name;
,第二个:tc.module2 = n.LastChild.Name;
然而,我认为这并不是一种"正确"的做事方式。
是的,您可以使用XPath实现这一点。
实际上,在变量或XML元素中永远不应该有计数器数字,但要使用现有内容,这(或类似内容)将适用于2个年级/科目。
// First loop through each student
foreach( XmlElement ndStudent in xd.SelectNodes( "/students/Evening | /students/Day" ) {
// Build your object from the data
Student tc = new Student();
tc.id = ndStudent.GetAttribute( "id" );
tc.name = ndStudent.GetAttribute( "id" );
// Add in the grades
foreach( XmlElement ndGrade in ndStudent( "grades/*/grade1" ) ) {
tc.grade1 = ndGrade.innerText;
}
// Add in the grades
foreach( XmlElement ndGrade in ndStudent( "grades/*/grade2" ) ) {
tc.grade2 = ndGrade.innerText;
}
} // end of student loop