简体   繁体   中英

How to deserialize XML returned from REST API call?

I am stuck deserializing the returned XML from a RESTful API call. This is the error message I am getting back:

System.AggregateException : One or more errors occurred. ----> System.Runtime.Serialization.SerializationException : Error in line 1 position 106. Expecting element 'ArrayOfAPIUtility.PartInfo' from namespace ' http://schemas.datacontract.org/2004/07/MyProject.Web '.. Encountered 'Element' with name 'Part', namespace ''.

I followed this stackoverflow answer to create a successful REST connection.

The returned XML looks like this:

<Part>
    <ItemId>12345</ItemId>
    <ItemDescription>Item Description</ItemDescription>
    <Cost>190.59</Cost>
    <Weight>0.5</Weight>
</Part>

I am trying to to deserialize it like this:

public class PartInfo
{
    public string ItemId { get; set; }
    public string ItemDescription { get; set; }
    public string Cost { get; set; }
    public string Weight { get; set; }
}

public void GetPartInfo(string itemId)
{
    var URL = ...some URL...;
    client.BaseAddress = new Uri(URL);

    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

    HttpResponseMessage response = client.GetAsync(urlParameters).Result;
    if (response.IsSuccessStatusCode)
    {
        var dataObjects = response.Content.ReadAsAsync<IEnumerable<PartInfo>>().Result;
        foreach (var d in dataObjects)
        {
            Console.WriteLine("{0}", d.ItemId);
        }
    }
}

The result is the error message pasted above.

I think I am missing something very elementary here :-)

Thank you very much for your help!

Try xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication48
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);  //use parse instead if input is a string
            PartInfo partInfo = doc.Elements("Part").Select(x => new PartInfo()
            {
                ItemId = (string)x.Element("ItemId"),
                ItemDescription = (string)x.Element("ItemDescription"),
                Cost = (decimal)x.Element("Cost"),
                Weight = (double)x.Element("Weight")
            }).FirstOrDefault();

        }
    }
    public class PartInfo
    {
        public string ItemId { get; set; }
        public string ItemDescription { get; set; }
        public decimal Cost { get; set; }
        public double Weight { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM