【发布时间】:2020-10-16 10:56:42
【问题描述】:
在写这个问题之前,我尝试了this、this和this的方法。我花了一整天都没有得到结果。
我有自己的 REST API,它在 XML 文件中返回序列化的 List<T>
[ActionName("planes")]
[HttpGet]
public IEnumerable<Planes> GetPlanes()
{
using (DB_A5vehiclesEntities entities = new DB_A5_vehiclesEntities())
{
return entities.Planes.ToList();
}
}
生成的 XML 文件如下所示 (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
我的代码:
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);
}
我得到错误:System.Xml.XmlException:'根级别的数据无效。第 1 行,位置 1
我想要的只是连接到 API,反序列化 XML 并获得带有所有 XML 元素的List<T>。
怎么做才对?
【问题讨论】:
-
您的问题(恕我直言)没有解释您的实际错误是什么。问题是将您的数据映射到 XML 结构,从您的 API 或其他东西返回 Json(不是 XML)?
-
@Kane 更新问题
-
格式良好的 XML 只有一个根标记。所以当你有一个像你所做的那样的列表时,XML 序列化器会失败:typeof(List
)。所以你需要两个类Planes和Plane。然后在序列化程序中有:typeof(Planes)。然后在 Planes 中有 public List Planes -
没有用户代理和接受 JSON 被返回。所以有两个问题。有关工作结果,请参阅我的答案。在浏览器中手动获取结果是 xml,但是当我签入我的 c# 代码时它是 JSON。我不得不使用嗅探器检查浏览器结果中的标头,然后在 c# 代码中使用相同的标头。
标签: c# xml list rest serialization