8
  <Sections>
    <Classes>
      <Class>VI</Class>
      <Class>VII</Class>
    </Classes>
    <Students>
      <Student>abc</Student>
      <Student>def</Student>
    </Students>    
  </Sections>

我必须遍历 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
        }

无法获得所有课程。此外,我需要在使用 LINQ to XML 的情况下重写它,即使用 XmlNodeList 和 XmlNodes。

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

不知道该怎么做。

4

3 回答 3

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;
}
于 2011-06-09T16:20:26.200 回答
1

不确定是否要为 XmlNodes 重写它,但对于您的班级和学生,您可以简单地:

   XDocument doc.Load("File.xml");
   foreach(XElement c in doc.Descendants("Class")) 
   {   
       // do something with c.Value; 
   }

   foreach(XElement s in doc.Descendants("Student")) 
   {   
       // do something with s.Value; 
   }
于 2011-06-09T16:19:33.163 回答
1

使用 LINQ to XML:

XDocument doc = XDocument.Load("file.xml");
var classNodes = doc.Elements("Sections").Elements("Classes").Elements("Class");
StringBuilder result = new StringBuilder();
foreach( var c in classNodes )
    result.Append(c.Value).Append(",");

使用 XPath:

XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
var classNodes = doc.SelectNodes("/Sections/Classes/Class/text()");
StringBuilder result = new StringBuilder();
foreach( XmlNode c in classNodes )
    result.Append(c.Value).Append(",");
于 2011-06-09T16:23:49.613 回答