Search code examples
c#xmlserializationdeserialization

Cannot figure out why this particular line is messing up the C# xml deserializer


I have verified with multiple XML validators to ensure the document is sound.

In one area of the document, anything after it the C# debugger will say the first character of the next line (after indent; did try having the entire document with none as well) is not formatted correctly:

System.InvalidOperationException: There is an error in XML document (11, 5).
System.FormatException: Input string was not in a correct format

Here is the reader/deserialize part of the code:

XmlSerializer serializer = new XmlSerializer(typeof(VehicleModelInfo));

using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
{
    try
    {
        return (VehicleModelInfo) serializer.Deserialize(reader);
    }
    catch (System.InvalidOperationException e)
    {
        Console.WriteLine(e);
        // [...]
    }
}

This is the problematic line:

<PovCameraVerticalAdjustmentForRollCage value="0.000000" />

It, along with the other elements in the XML, are declared:

[XmlElement("PovCameraVerticalAdjustmentForRollCage")]
public float PovCameraVerticalAdjustmentForRollCage { get; set; }

I cannot figure out why this one (there are many other float values in the XML) in particular is not behaving.

Any advice would be appreciated.


Solution

  • Your setup using [XmlElement("PovCameraVerticalAdjustmentForRollCage")] requires that the xml data needs to look like below one.

    <PovCameraVerticalAdjustmentForRollCage>0.000000<PovCameraVerticalAdjustmentForRollCage>
    

    But it doesn't; instead, <PovCameraVerticalAdjustmentForRollCage value="0.000000" /> is an xml element with the value you are looking for in an attribute named value.

    In order to deserialize that one, your VehicleModelInfomodel needs a PovCameraVerticalAdjustmentForRollCage property to a type having such a Value property, for example:

    public class VehicleModelInfo
    { 
        public PovCameraVerticalAdjustmentForRollCage PovCameraVerticalAdjustmentForRollCage { get; set; }
    } 
    
    public class PovCameraVerticalAdjustmentForRollCage
    {
        [XmlAttribute("value")]
        public float Value { get; set; }
    }