循环遍历XML中的多个子节点

use*_*709 8 c# xml xmlnodelist xmlnode linq-to-xml

  <Sections>
    <Classes>
      <Class>VI</Class>
      <Class>VII</Class>
    </Classes>
    <Students>
      <Student>abc</Student>
      <Student>def</Student>
    </Students>    
  </Sections>
Run Code Online (Sandbox Code Playgroud)

我必须遍历Classes才能将'Class'变成一个字符串数组.我还必须循环"学生",让'学生'进入一系列字符串.

XDocument doc.Load("File.xml");
     string str1;
     foreach(XElement mainLoop in doc.Descendants("Sections")) 
       {   
          foreach(XElement classLoop in mainLoop.Descendants("Classes"))
                str1 = classLoop.Element("Class").Value +",";
       //Also get Student value
        }
Run Code Online (Sandbox Code Playgroud)

没有努力获得所有课程.另外,我需要在使用LINQ to XML的情况下重写它,即使用XmlNodeList和XmlNodes.

XmlDocument doc1 = new XmlDocument();
doc1.Load("File.xml");
foreach(XmlNode mainLoop in doc.SelectNodes("Sections")) ??
Run Code Online (Sandbox Code Playgroud)

不确定如何去做.

Ahm*_*eed 4

XPath 很简单。要将结果放入数组中,可以使用 LINQ 或常规循环。

var classNodes = doc.SelectNodes("/Sections/Classes/Class");
// LINQ approach
string[] classes = classNodes.Cast<XmlNode>()
                             .Select(n => n.InnerText)
                             .ToArray();

var studentNodes = doc.SelectNodes("/Sections/Students/Student");
// traditional approach
string[] students = new string[studentNodes.Count];
for (int i = 0; i < studentNodes.Count; i++)
{
    students[i] = studentNodes[i].InnerText;
}
Run Code Online (Sandbox Code Playgroud)