xmlxml-serialization

XmlSerializer skipping items in non-pretty format xml


In case my xml file has the non-pretty format:

<ArrayOfColumn><Column><COLUMN_NAME>SomeName1</COLUMN_NAME></Column><Column><COLUMN_NAME>SomeName2</COLUMN_NAME></Column></ArrayOfColumn>

This code skip the second column (or every second item in case there are more than two):

using (var xmlReader = XmlReader.Create(fileStream))
{
    var serializer = new XmlSerializer(typeof(MyColumnClass), new XmlRootAttribute("Column"));
    var myColumnClass= new List<MyColumnClass>();
    while (xmlReader.ReadToFollowing("Column"))
    {
        list.AddRange(new List<MyColumnClass>() { (MyColumnClass)serializer.Deserialize(xmlReader) });
    // rest of code
}

While my xml has the pretty format it works perfectly:

<ArrayOfColumn>
    <Column>
        <COLUMN_NAME>SomeName1</COLUMN_NAME>
    </Column>
    <Column>
        <COLUMN_NAME>SomeName2</COLUMN_NAME>
    </Column>
</ArrayOfColumn>

How to adjust the code so it will support non-pretty xml format?


Solution

  • Issue is not pretty. It is when you read the next element you are already at the next element and skip every other element. Try following which I have been using for years

    while (!xmlReader.EOF)
    {
       if(xmlReader.Name != "Column")
       {
          xmlReader.ReadToFollowing("Column");
       }
       if (!xmlReader.EOF)
       {
          list.AddRange(new List<MyColumnClass>() { (MyColumnClass)serializer.Deserialize(xmlReader) });
          // rest of code
       }                        
    }