Reading XML with XmlReader class

John 'Mark' Smith

I have an XML file in the following format:

<Votes>
   <Candidate>
      <CandidateName>Boris Johnson</CandidateName>
   </Candidate>
   <Vote>
      <VoteString>1 3 6 2 9 7 4 5 8</VoteString>
   </Vote>
</Votes>

I want to first read the CandidateName and then the VoteString. I am using the following code:

using (XmlReader reader = XmlReader.Create(filepath))
{
   if (reader.IsStartElement())
   {
      switch (reader.Name)
      {
         case "Candidate":
         string name = reader["CandidateName"];
         break;

         case "Vote":
         string voteStr = reader["VoteString"];
         break;
      }
   }
}

What happens in debug is that reader.Name is set to "Votes" and the two cases in my switch statement never get triggered. I've looked through the XmlReader methods to find something that lists all the elements but there is nothing.

I've not worked directly with XML files before so I'm not sure if the XML format is used is correct. Am I going about this the right way?

wakers01

XML reader is going to read through each element in the XML tree, so you just need to keep going if you haven't hit the nodes you want yet by putting the reader in a loop. You're code needs to continue to loop through the XML, so it would need to look a little more like this:

using (XmlReader reader = XmlReader.Create(filepath))
{
   while(reader.Read())
   {
      if (reader.IsStartElement())
      {
         switch (reader.Name)
         {
            case "Candidate":
            string name = reader["CandidateName"];
            break;

            case "Vote":
            string voteStr = reader["VoteString"];
            break;
         }
      }
   }
}

Of course, the more important question here is what are you trying to do with those values you are getting? Your current code doesn't actually do anything with the values except assign them to a variable that goes out of scope immediately.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related