有没有办法在没有实际输入'math','physics'或'technologija'的情况下使用SelectSingleNode
以便我可以用任何条目阅读它?
到目前为止,阅读内容如下:
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;
...
此外,由于有“晚上”和“日”学生,我应该使用另一个节点列表/ foreach(XmlNodeList nodelist = xd.SelectNodes("/students/Evening");
)来阅读它们,或者我可以以某种方式合并/students/Evening
和{{1} }?
XML文件:
students/Day
答案 0 :(得分:1)
不知道我的问题是不是太明确或者什么,但我终于找到了如何正确地做到这一点:
首先,要获取module1我使用tc.module1 = n.FirstChild.Name;
,第二个:tc.module2 = n.LastChild.Name;
然而,我认为这并不是一个真正正确的问题。做事的方式。
答案 1 :(得分:0)
是的,你可以用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