XML反序列化的错误:不期望{“<query xmlns =”“>。”} </query>

时间:2014-02-12 21:37:16

标签: c# xml visual-studio-2012 serialization

更新:我已经解决了这个问题。称为类符号的模型已更新,现在可以正确地反序列化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 -->

1 个答案:

答案 0 :(得分:0)

看来,你应该改变

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

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

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

[XmlRoot("query")]