簡體   English   中英

如何反序列化從REST API調用返回的XML?

[英]How to deserialize XML returned from REST API call?

我被困從RESTful API調用反序列化返回的XML。 這是我得到的錯誤消息:

System.AggregateException:發生一個或多個錯誤。 ----> System.Runtime.Serialization.SerializationException:第1行位置106出錯。應從命名空間“ http://schemas.datacontract.org/2004/07/MyProject.Web ”獲取元素“ ArrayOfAPIUtility.PartInfo”。遇到名稱為“ Part”,名稱空間為“''的“元素”。

我遵循這個stackoverflow答案來創建成功的REST連接。

返回的XML如下所示:

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

我試圖像這樣反序列化:

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);
        }
    }
}

結果是上面粘貼的錯誤消息。

我想我在這里缺少一些非常基本的東西:-)

非常感謝您的幫助!

試試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; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM