【问题标题】:Deserializing with c# unsuccessful用c#反序列化不成功
【发布时间】:2012-02-21 11:01:10
【问题描述】:

我正在尝试反序列化这个 xml:

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
yahoo:count="10" yahoo:created="2012-02-20T19:07:02Z" yahoo:lang="en-US">
<results>
    <a href="/dir/index?sid=396545299">Books &amp; Authors</a>
    <a href="/dir/index?sid=396545374">Dancing</a>
    <a href="/dir/index?sid=396546034">Genealogy</a>
    <a href="/dir/index?sid=396545298">History</a>
    <a href="/dir/index?sid=396545310">Other - Arts &amp; Humanities</a>
    <a href="/dir/index?sid=396545300">Performing Arts</a>
    <a href="/dir/index?sid=396545231">Philosophy</a>
    <a href="/dir/index?sid=2115500137">Poetry</a>
    <a href="/dir/index?sid=396546419">Theater &amp; Acting</a>
    <a href="/dir/index?sid=396545309">Visual Arts</a>
</results>
</query>

这是yahoo api在查询类别和子类别时返回的xml。

这段代码应该反序列化它:

string query_string = "some_url";

        HttpWebRequest request = HttpWebRequest.Create
            (query_string) as HttpWebRequest;

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());

            System.Xml.Serialization.XmlSerializer serializer = new 

            System.Xml.Serialization.XmlSerializer(typeof(queryA));

            queryA Q = (queryA)serializer.Deserialize(reader); // THIS IS WHERE THE EXCEPTION IS THROWN

            reader.Close();
        }

我得到一个异常提示:XML 文档 (2, 2) 中存在错误

异常详情:

"<query xmlns=''> was not expected."

课程如下:

namespace Yahoo_answers_tool {
using System.Xml.Serialization;


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class queryA {

    private queryResultsA[] resultsField;

    private string countField;

    private string createdField;

    private string langField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlArrayItemAttribute("a", typeof(queryResultsA), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public queryResultsA[] results {
        get {
            return this.resultsField;
        }
        set {
            this.resultsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
    public string count {
        get {
            return this.countField;
        }
        set {
            this.countField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
    public string created {
        get {
            return this.createdField;
        }
        set {
            this.createdField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
    public string lang {
        get {
            return this.langField;
        }
        set {
            this.langField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class queryResultsA {

    private string hrefField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string href {
        get {
            return this.hrefField;
        }
        set {
            this.hrefField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSetA {

    private queryA[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("query")]
    public queryA[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

}

有什么想法吗?

【问题讨论】:

  • 我怀疑它不喜欢命名空间。
  • 哪个工具生成了该代码?我使用 Xsd2Code,从来没有遇到过这样的问题。你生成的代码对我来说看起来很奇怪(类的命名)
  • 您尝试过这里描述的内容吗? [将 Xml 反序列化为对象时出错 - xmlns='' 不是预期的][1] [1]: stackoverflow.com/questions/4884383/…
  • 你为什么要反序列化它,为什么不简单地使用 Linq To Xml 或其他 XML perser 来获取你想要的数据?
  • @BlueM 我正在​​使用 Visual Studio 自带的 XSD.exe

标签: c# deserialization xmlserializer


【解决方案1】:

根据我的评论,我将使用 Linq to Xml 解析 XML,下面的代码可以正常工作,但是我建议在 Using 语句之外分离解析,以便您可以处理 Response 和 Streamreader。

    public static YahooQueryResult LoadYahooResults(string url)
    {
        YahooQueryResult result = null;

        WebRequest request = WebRequest.Create(path);
        request.Timeout = 5000;

        try
        {
            using (WebResponse response = request.GetResponse())
            {                                                                                        
                XDocument doc = XDocument.Load(response.GetResponseStream());

                if (doc != null)
                {
                    var query = doc.Root;

                    // Query Attribute Values
                    var count = int.Parse(query.Attributes().First(c => c.Name.LocalName == "count").Value);
                    var created = query.Attributes().First(c => c.Name.LocalName == "created").Value;
                    var lang = query.Attributes().First(c => c.Name.LocalName == "lang").Value;
                    var results = doc.Descendants().FirstOrDefault(r => (r.Name.LocalName == "results")).Descendants().Select(a => new Result() { ID = int.Parse(a.Attribute("href").Value.Replace("/dir/index?sid=", string.Empty).Trim()), Href = a.Attribute("href").Value, Text = a.Value }).ToList();

                    result = new YahooQueryResult() { Lang = lang, Created = created, Count = count, Results = results };

                }
            }
        }
        catch (Exception ex)
        {
            // Handle Exception
        }

        return result;
    }


    public class Result
    {
        public int ID { get; set; }
        public string Href { get; set; }
        public string Text { get; set; }
    }

    public class YahooQueryResult
    {
        public string Lang { get; set; }
        public string Created { get; set; }
        public int Count { get; set; }
        public IEnumerable<Result> Results { get; set; }

    }

【讨论】:

  • 谢谢你,我试了一下,让你知道结果如何。有没有办法从结果和值中获取 href 链接中的 ID 号?
  • @user1188712 如果它像删除'/dir/index?sid='那么简单,然后更改代码并添加ID并添加此代码... ID = int.Parse(a.Attribute( "href").Value.Replace("/dir/index?sid", string.Empty).Trim())
  • 非常感谢,这很好用。您可以添加上一条评论的代码,使其也包含 ID 变量吗?还有一个问题 - 尝试后您将如何处理异常?
  • @user1188712 幸运我今天下午很无聊!
  • @user1188712 使用真实 ID 登录并学习贡献,无论对错,它让每个人都成为更好的程序员!
猜你喜欢
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
相关资源
最近更新 更多