我试图通过httpclient使用REST API来获取数据,遇到解析问题,{“第1行第95位错误.期望来自命名空间’ http://schemas.datacontract.org/2004/07/‘的元素’工作流’.遇到名为’工作流’的’元素’,命
客户端代码是
string baseUri = "/rest/workflows/";
client = CreateClient(baseUri);
HttpRequestMessage request = CreateRequest(baseUri);
var task = client.SendAsync(request);
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<collection>().ContinueWith(wf =>
{
Console.WriteLine(wf.Result.workflow.Length);
});
数据类
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2005/Atom", IsNullable = false)]
public partial class collection
{
private workflow[] workflowField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("workflow", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public workflow[] workflow
{
get
{
return this.workflowField;
}
set
{
this.workflowField = value;
}
}
}
并且响应xml文件采用此格式
<collection xmlns:ns2="http://www.w3.org/2005/Atom">
<workflow uuid="5ffbde8c-c430-4851-9c83-164c102a4d68">
<name>Remove a Volume</name>
<categories>
<category>Decommissioning</category>
</categories>
</workflow>
</collection>
我可以通过使用response.Content.ReadAsStringAsync()获取字符串并将其保存到xml文件,然后,我将其deserilize到集合,可以成功,但需要和serizliazer的默认命名空间
XmlSerializer serializer = new XmlSerializer(typeof(collection), "xmlns:ns2=\"http://www.w3.org/2005/Atom\"");
c = serializer.Deserialize(stream) as collection;
任何人都可以提供帮助
您不应该从xsd.exe工具触摸生成的文件.通过设置UseXmlSerializer = true,只需显式设置您希望使用XmlSerializer而不是默认情况下使用XmlMediaTypeFormatter使用的DataContractSerializer.
所以你必须创建一个像这样的特定类型格式化程序:
var formatters = new List<MediaTypeFormatter>() {
new XmlMediaTypeFormatter(){ UseXmlSerializer = true } };
并将其用作ReadAsAsync方法的参数:
private async Task<T> ReadAsync<T>(HttpResponseMessage response) => await response.Content.ReadAsAsync<T>(formatters);
