我无法从RESTful API调用反序列化返回的XML。 这是我要回复的错误消息:
System.AggregateException:发生了一个或多个错误。 ----> System.Runtime.Serialization.SerializationException:第1行中的错误 106.期待元素' ArrayOfAPIUtility.PartInfo'从 命名空间 ' http://schemas.datacontract.org/2004/07/MyProject.Web' .. 遇到过元素'名称'部分',名称空间''。
我按照this 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);
}
}
}
结果是上面粘贴的错误消息。
我想我在这里缺少一些非常基本的东西: - )
非常感谢你的帮助!
答案 0 :(得分:0)
试试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; }
}
}