-->

Why is my XML reader reading every other element?

2020-04-11 07:01发布

问题:

I've built a very simple table that displays 4 columns and 4 rows. When the following code is executed it displays every other element in the .xml file. It does not discriminate per table row. It reads through without any problem and I have run xml validators so it not a syntax issue.

public partial class lblXmlOutput : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ConformanceLevel = ConformanceLevel.Document;
        settings.IgnoreWhitespace = true;
        settings.IgnoreComments = true;

        XmlReader reader = XmlReader.Create(Server.MapPath("Part2XMLex.xml"), settings);

        string result = "";

        while (reader.Read())
        {
            if (reader.IsStartElement("td"))
                result += reader.ReadElementContentAsString();

            txtOutput.Text = result;
        }
   }
}

回答1:

Because both .Read() and .ReadElementContentAsString() (the parameterless overload) move the reader to the next node.

Change your while condition to:

while (!reader.EOF)

Then add:

else reader.Read();