我正在尝试创建一个控制台应用程序客户端,该客户端可以连接到示例 API 并显示其中的数据。
架构:http://feed.elasticstats.com/schema/soccer/sr/v2/teams-standing.xsd
Feed 格式示例:http://developer.sportsdatallc.com/files/soccer_v2_standings.xml
从架构生成的类文件非常大,但我会举一个实例的例子,我尝试获取类属性的输出。
架构中的类文件
public partial class simpleTeam {
private string idField;
private string aliasField;
private string nameField;
private string country_codeField;
private string countryField;
private teamType typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string alias {
get {
return this.aliasField;
}
set {
this.aliasField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string country_code {
get {
return this.country_codeField;
}
set {
this.country_codeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string country {
get {
return this.countryField;
}
set {
this.countryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public teamType type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
}
这是我的客户端类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace UpdateUefaClient
{
internal class Program
{
private static async Task Run()
{
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress =
new Uri("http://api.sportsdatallc.org/soccer-t2/eu/teams/standing.xml?api_key="my key to get the live feed(same as feed format)");
// base URL for API Controller i.e. RESTFul service
// add an Accept header for JSON
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 1
HttpResponseMessage response = await client.GetAsync(""); // accessing the Result property blocks
if (response.IsSuccessStatusCode) // 200.299
{
// read result
var team = await response.Content.ReadAsAsync<IEnumerable<simpleTeam>>();
foreach (var t in team)
{
Console.WriteLine(t.id);
}
}
else
{
Console.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void Main()
{
Run().Wait();
}
}
}
运行后,我得到以下内容
System.Runtime.Serialization.SerializationException: Error in line 1 position 12
1. Expecting element 'ArrayOfsimpleTeam' from namespace 'http://schemas.datacont
ract.org/2004/07/'.. Encountered 'Element' with name 'standings', namespace 'ht
tp://feed.elasticstats.com/schema/soccer/sr/v2/teams-standing.xsd'.
at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(Xml
ReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataCo
ntractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleException
s(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver data
ContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader r
eader)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass3.<ReadF
romStreamAsync>b__2()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func,
CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at UpdateUefaClient.Program.<Run>d__0.MoveNext() in c:UsersDanielDocuments
Visual Studio 2013ProjectsUpdateUefaClientUpdateUefaClientProgram.cs:line 3
3
Press any key to continue . . .
我已经尝试了最简单的样本(id),但这给了我一个错误。不知道出了什么问题。任何建议将不胜感激
@Robert McKee是对的。您正在反序列化standings
而不是simpleTeam
.
private static standings WebDeserialize()
{
standings s = null;
var srlz = new XmlSerializer(typeof(standings));
//
var uri = "http://developer.sportsdatallc.com/files/soccer_v2_standings.xml";
var xmlReader = XmlReader.Create (uri);
s = (standings)srlz.Deserialize(xmlReader);
return s;
}
static async Task AsyncWebDeserialize()
{
Task<standings> task = Task.Run<standings>(() => WebDeserialize());
standings s = await task;
Console.WriteLine("Cat:{0} Gen:{1}", s.categories.Length, s.generated);
}
这样称呼:AsyncWebDeserialize().Wait()