简体   繁体   English

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

[英]Loop through multiple subnodes in XML

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

I have to loop through Classes to get 'Class' into an array of strings.我必须遍历 Classes 才能将“Class”放入字符串数组中。 I have to also loop through 'Students' to get 'Student' put into an array of strings.我还必须遍历“学生”以将“学生”放入字符串数组中。

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
        }

is not working to get all the classes.无法获得所有课程。 Also, I need to rewrite this without using LINQ to XML, ie using XmlNodeList and XmlNodes.另外,我需要在使用 LINQ 到 XML 的情况下重写它,即使用 XmlNodeList 和 XmlNodes。

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

Not sure how to go about it.不知道如何 go 关于它。

The XPath is straightforward. XPath 很简单。 To get the results into an array you can either use LINQ or a regular loop.要将结果放入数组中,您可以使用 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;
}

Not sure about rewriting it for XmlNodes but for your Classes and Students you can simply:不确定是否要为 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; 
   }

With LINQ to XML:使用 LINQ 至 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(",");

With XPath:使用 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(",");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM