0

I am attempting to send an XML file from my Angular application to my ASP .Net Core controller. I would like the controller to receive the file and then deserialize it to a strongly typed list of objects. What is the correct way to go about this? I am currently receiving an error when the file is being deserialized which is stating 'Data at the root level is invalid. Line 1, position 1'. Below is what I have tried so far.

Controller:

    [HttpPost("reconciliation")]
    public async Task<IActionResult> SetReconciliation(IFormFile file)
    {
        List<ReconciliationExportCsv> records = new List<ReconciliationExportCsv>();
        XmlSerializer serializer = new XmlSerializer(typeof(List<ReconciliationExportCsv>));

        using (var reader = new StreamReader(file.OpenReadStream()))
        {
           records = (List<ReconciliationExportCsv>)serializer.Deserialize(reader);
        }

        var submitted = await _service.UploadReconciliationData(records);

        return Ok();
    }
}

Model:

public class ReconciliationExportCsv
{
    public string or1 { get; set; }
    public string exitStatus { get; set; }
    public string vendorState { get; set; }
   }
}

CSV:

enter image description here

Gearoid Sheehan
  • 198
  • 1
  • 19
  • A well formed xml file has only one tag at the root. You are trying to serialize an array (List) which is giving the error. The solution is to create a root class and put the array into the root. – jdweng Apr 22 '20 at 13:25
  • What does the XML look like? That error generally indicates that the root XML element name or namespace does not match the expected name or namespace. To see where you might be going wrong, try serializing a `List` and comparing the generated XML with the XML you are trying to deserialize. Or, use one of the tools from [Generate C# class from XML](https://stackoverflow.com/q/4203540/3744182) to generate a data model matching the incoming XML. – dbc Apr 22 '20 at 14:24

1 Answers1

0

To convert from IFormFile to XDocument use syntax like that:

public async Task<IActionResult> Upload(IFormFile input)
{
    using (MemoryStream str = new MemoryStream())
            {
                await input.CopyToAsync(str);
                str.Position = 0;
                var xml = XDocument.Load(str);
             }
}

Then you can use XDocument class methods to work with your xml

ProgShiled
  • 154
  • 1
  • 1
  • 12