Deserialization from REST API XML to List<T> C#

亡梦爱人 提交于 2021-01-29 08:43:48

问题


Before writing this question, I tried this, this and this method. I spent the whole day on it and could not get the result.

I have my own REST API which returns a serialized List<T> in XML file

    [ActionName("planes")]
    [HttpGet]
    public IEnumerable<Planes> GetPlanes()
    {
        using (DB_A5vehiclesEntities entities = new DB_A5_vehiclesEntities())
        {
            return entities.Planes.ToList();
        }
    }

Generated XML file looks like this (link to xml file):

<ArrayOfPlanes xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/VehicleDataAccess">
  <Planes>
    <FirstFlyYear>1932</FirstFlyYear>
    <Id>18</Id>
    <Name>18</Name>
    //other values
</Planes>
//other items

My code:

IList<Plane> myList = null;

        string xml = @"http://bo7145907-001-site2.ftempurl.com/wtvapi/vehicles/planes";
        XmlSerializer serializer = new XmlSerializer(typeof(List<Plane>));
        using (StringReader reader = new StringReader(xml))
        {

            myList = serializer.Deserialize(reader) as List<Plane>;
        }

        textMessage = FindViewById<TextView>(Resource.Id.message);

    }

And i get the error: System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1

All I want is just connect to API, deserialize XML and get List<T> with all XML elements. How to do it right?


回答1:


Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string URL = "http://bo7145907-001-site2.ftempurl.com/wtvapi/vehicles/planes";
        static void Main(string[] args)
        {

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US\r\n");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\r\n";
            request.Accept = "text/html,application/xhtml+xml,application/xml\r\n";

            WebResponse response = request.GetResponse();

            XmlReader xReader = XmlReader.Create(response.GetResponseStream());

            XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfPlanes));
            ArrayOfPlanes planes = (ArrayOfPlanes)serializer.Deserialize(xReader);
 
        }
    }
    [XmlRoot(ElementName = "ArrayOfPlanes", Namespace = "http://schemas.datacontract.org/2004/07/VehicleDataAccess")]
    public class ArrayOfPlanes
    {
        [XmlElement(ElementName = "Planes", Namespace = "http://schemas.datacontract.org/2004/07/VehicleDataAccess")]
        public List<Planes> Plains { get; set; }
    }
    public class Planes
    {
    }
}



回答2:


Using HttpClient provides concise and efficient code.

string url = "http://bo7145907-001-site2.ftempurl.com/wtvapi/vehicles/planes";
var serializer = new XmlSerializer(typeof(ArrayOfPlanes));
ArrayOfPlanes arrayOfPlanes;

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Accept", "text/xml");

    using (var stream = await client.GetStreamAsync(url))
    {
        arrayOfPlanes = (ArrayOfPlanes)serializer.Deserialize(stream);
    }
}

Set of classes.

[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/VehicleDataAccess")]
public class ArrayOfPlanes
{
    [XmlElement(Namespace = "http://schemas.datacontract.org/2004/07/VehicleDataAccess")]
    public List<Planes> Planes { get; set; }
}

public class Planes
{
    public bool AAMissile { get; set; }
    // ...
}


来源:https://stackoverflow.com/questions/62584587/deserialization-from-rest-api-xml-to-listt-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!