反序列化 XML 时出错:{"<query xmlns=''> 不是预期的。"}

更新:我已经解决了这个问题。名为类符号的模型已更新,现在可以正确反序列化 XML。哇!我的对象现在可以正确反序列化。

我通常使用 json,但必须使用 XML 才能使用这些数据。

我已经尝试了几种不同的方法,但无法反序列化。它抛出的典型错误是:

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

我认为这就是我设置 Query 类的方式。我尝试了几种不同的方法,但都没有运气。希望对XML有更多了解的人能给点建议。谢谢。

这是我从控制台应用程序调用的 GetResult 方法。

    public static Query GetResults()
    {
        string url = @"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        Query resultSet;

        using (WebResponse response = request.GetResponse()) {
            using (Stream responseStream = response.GetResponseStream()) {
                XmlSerializer serializer = new XmlSerializer(typeof(Results));
                resultSet = (Query)serializer.Deserialize(responseStream);
            }
        }
        return resultSet;
    }

这是Results 类: 注意: 该类已经过修改,可以与XML 一起正常工作。这现在有效!

namespace TheXMLService
{
[XmlRoot("query", Namespace = "")]
public class Symbols
{
    [XmlArrayItem("industry", typeof(Industry))]
    public List<Industry> results { get; set; }
}
public class Industry
{
    [XmlAttribute()]
    public int id { get; set; }
    [XmlAttribute()]
    public string name { get; set; }
    [XmlElement("company", typeof(Company))]
    public Company[] company;
}
public class Company
{
    [XmlAttribute()]
    public string name;
    [XmlAttribute()]
    public string symbol;
}
}

这是返回的一大块 xml:

<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="215"     yahoo:created="2014-02-12T18:40:10Z" yahoo:lang="en-US">

<results>
<industry id="112" name="Agricultural Chemicals">
<company name="Adarsh Plant Protect Ltd." symbol="ADARSHPL.BO"/>
<company name="AgriTec Systems, Inc." symbol="AGR.V"/>
<company name="Agrium Inc" symbol="AGU.DE"/>

... (many more companies here...

<company name="United Utilities Group PLC" symbol="UUEC.DE"/>
</industry>
</results>
</query>
<!-- total: 3288 -->
<!-- engine2.yql.bf1.yahoo.com -->
stack overflow Errors de-serializing XML: {"<query xmlns=''> was not expected."}
原文答案

答案:

作者头像

看来,你应该改变

XmlSerializer serializer = new XmlSerializer(typeof(Results));

XmlSerializer serializer = new XmlSerializer(typeof(Query));

[XmlRoot("query", Namespace = "http://www.yahooapis.com/v1/base.rng")]

[XmlRoot("query")]