Iterate through xml file and store content inside Textfield c#

1.8k Views Asked by At

I have an Xml file where I want to loop through each module node which increments by 1. Here is a sample of my xml file:

<PersonDetails>
  <PersonTitle>Teacher</PersonTitle>
  <Keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
      <subjectscore />
    </Subject>
    <Subject>
      <subjectName>science</subjectName>
      <subjectId>sla1s</subjectId>
      <subjectvalue>25</subjectvalue>
      <subjectscore />
    </Subject>
  </Keystage3>
</PersonDetails>

I want to loop through the xml file and get all data of Subject for both <Subject> node and store each value inside a variable.

I have a piece of code which gets the value from a specific node and outputs it on a textfield.

here is the code I have so far:

public partial class Form1 : Form
{
    private string subName, subId, subvalue;

    public XmlDocument Doc;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlNodeType type;

        while (reader.Read()) {

            type = reader.NodeType;

            if(type == XmlNodeType.Element)
            {

                    if (reader.Name == "subjectName")
                    {
                        reader.Read();
                        textBox1.Text = reader.Value;
                    }
                    if (reader.Name == "subjectId")
                    {
                        reader.Read();
                        textBox2.Text = reader.Value;
                    }
                    if (reader.Name == "subjectvalue")
                    {
                        reader.Read();
                        textBox3.Text = reader.Value;
                   }


            }
        }
        reader.Close();


    }

How can I make it so that the output recieved is something like:

{maths,qq1,20}
{science,sla1s,25}
2

There are 2 best solutions below

3
On BEST ANSWER

Using some LINQ-Magic you can do the folowing:

XElement root = XElement.Load("data.xml");
        var subjects = from subject in root.Descendants()
                          where subject.Name.LocalName.Contains("Subject")
                          select new
                          {
                              SubjectName = subject.Element("subjectName").Value,
                              SubjectId = subject.Element("subjectId").Value,
                              SubjectValue = subject.Element("subjectvalue").Value
                          };

foreach (var subject in subjects)
{
    Console.WriteLine(subject);

    //you can use subject like this:
    string subjectName = subject.SubjectName;
    string subjectId = subject.SubjectId;
    string subjectValue = subject.SubjectValue;
}

This will print:

{ SubjectName = maths, SubjectId = qq1, SubjectValue = 20 }
{ SubjectName = science, SubjectId = sla1s, SubjectValue = 25 }

Includes:

using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
7
On

You can perform it by using XDocument. If you want to store the nodes values as a collection you can create a class for SubjectNode like this;

        public class SubjectNode
        {
            public string SubjectName { get; set; }
            public string SubjectId { get; set; }
            public string SubjectValue { get; set; }
        }

Then you can retrieve the data like this;

        var xdoc = XDocument.Load("data.xml");
        var keystageNode = xdoc.Descendants("Keystage3").FirstOrDefault();
        var iterateNode = keystageNode.FirstNode;
        var subjectNodes = new List<SubjectNode>();
        while (iterateNode != null)
        {
            var node = (XElement)iterateNode.NextNode;
            subjectNodes.Add(new SubjectNode
            {
                SubjectName = node.Element("subjectName").Value,
                SubjectId = node.Element("subjectId").Value,
                SubjectValue = node.Element("subjectvalue").Value
            });
            iterateNode = iterateNode.NextNode;
        }