Loop through multiple subnodes in XML
Asked Answered
O

3

8
  <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. 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, i.e using XmlNodeList and XmlNodes.

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

Not sure how to go about it.

Odont answered 9/6, 2011 at 16:12 Comment(1)
just remove the home from homework, that's what it is. ;)Odont
D
4

The XPath is straightforward. To get the results into an array you can either use LINQ or a regular loop.

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;
}
Disrupt answered 9/6, 2011 at 16:20 Comment(0)
O
1

Not sure about rewriting it for XmlNodes but for your Classes and Students you can simply:

   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; 
   }
Optimum answered 9/6, 2011 at 16:19 Comment(0)
R
1

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

With 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(",");
Rakel answered 9/6, 2011 at 16:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.