我正在尝试使用REST API来通过httpclient获取数据,遇到解析问题,{“第1行第95位错误。期望来自名称空间'http://schemas.datacontract.org/2004/07/'的元素'workflow'。.遇到名称为'workflow的'Element' ',名称空间“。”}

客户端代码是

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文件中,然后,我将其反序列化为集合,可以成功,但是需要serizliazer的默认名称空间

XmlSerializer serializer = new XmlSerializer(typeof(collection), "xmlns:ns2=\"http://www.w3.org/2005/Atom\"");
            c = serializer.Deserialize(stream) as collection;


任何人都可以为此提供帮助

最佳答案

您不应触摸从xsd.exe工具生成的文件。

只需通过设置XmlSerializer显式设置您要使用DataContractSerializer而不是默认使用XmlMediaTypeFormatterUseXmlSerializer = true

因此,您必须创建一个特定的类型格式化程序,如下所示:

var formatters = new List<MediaTypeFormatter>() {
                new XmlMediaTypeFormatter(){ UseXmlSerializer = true } };


并将其用作ReadAsAsync方法的参数:

private async Task<T> ReadAsync<T>(HttpResponseMessage response)
=> await response.Content.ReadAsAsync<T>(formatters);

10-04 21:40
查看更多