简体   繁体   中英

Reading XML with XmlReader class

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?

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.

XmlReader is good for fast, forward read, operations. You can accomplish what you're wanting to do by moving the reader forward with Read, Skip, and a whole host of other methods exposed by the reader, in a loop. Or, you can switch to XmlDocument and select the nodes by name, id, xpath, etc.

XmlReader: while(reader.Read()) { ... }

XmlDocument: XmlDocument doc = new XmlDocument(); doc.Load(filepath);

var nodes = doc.GetELementsByTagName("CandidateName"); nodes = doc.GetElementsByTagName("Vote");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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