[英]How to deserialize XML returned from REST API call?
I am stuck deserializing the returned XML from a RESTful API call. 我被困从RESTful API调用反序列化返回的XML。 This is the error message I am getting back:
这是我得到的错误消息:
System.AggregateException : One or more errors occurred.
System.AggregateException:发生一个或多个错误。 ----> 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 ''.
----> System.Runtime.Serialization.SerializationException:第1行位置106出错。应从命名空间“ http://schemas.datacontract.org/2004/07/MyProject.Web ”获取元素“ ArrayOfAPIUtility.PartInfo”。遇到名称为“ Part”,名称空间为“''的“元素”。
I followed this stackoverflow answer to create a successful REST connection. 我遵循这个stackoverflow答案来创建成功的REST连接。
The returned XML looks like this: 返回的XML如下所示:
<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 试试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.