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

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

我需要循环遍历Classes以将“Class”放入字符串数组中。 我还需要循环遍历“Students”以将“Student”放入字符串数组中。

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")) ??

不确定如何开始。


1
只需将“homework”中的“home”去掉,这就是它的含义。 ;) - user752709
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;
}

1

不确定如何为XmlNodes重写它,但对于您的Classes和Students,您可以简单地:

   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; 
   }

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(",");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接