Search code examples
c#while-loopxmlreader

XmlReader IsStartElement in a while loop is repeating the previous line


I have an XML that is structured like this:

<?xml version="1.0" encoding="utf-8"?>
<Report blah blah blah>
  <KeywordPerformanceReportColumns>
    <Column name="GregorianDate" />
    <Column name="AccountId" />
    <Column name="AccountNumber" />
    <Column name="AccountName" />
    <Column name="CampaignId" />
    <Column name="CampaignName" />
    etc....

From this SO post, I learned to use IsStartElement to loop through children of KeywordPerformanceReportColumns. I'm getting the behavior where it loops back to the first Column, never proceeding to the next child.

Code

//use xmlreader to read the memorystream
using (XmlReader reader = XmlReader.Create(memStream))
{
    while (reader.Read())
    {
        reader.ReadStartElement("Report");

        //schema information
        reader.ReadStartElement("KeywordPerformanceReportColumns");

        //columns
        while (reader.IsStartElement("Column"))
        {
            //note interested in whitespace nodes
            bool isWhiteSpace = reader.NodeType == XmlNodeType.Whitespace;

            if (!isWhiteSpace)
            {
                string columnName = reader.GetAttribute("name");
                Console.WriteLine(columnName);
            }
        }

        reader.ReadEndElement( /* "KeywordPerformanceReportColumns" */ );

        reader.ReadEndElement( /* "Report" */ );
    }
}

Screenshot

screen


Solution

  • In the example you've linked to and here the ReadToNextSibling method is used

    while (reader.ReadToNextSibling("SubEmptyElement"))
    

    and not the IsStartElement

     while (reader.IsStartElement("Column"))