【问题标题】:XML deserialization attempt yields empty objectXML 反序列化尝试产生空对象
【发布时间】:2014-12-19 21:46:39
【问题描述】:

我正在尝试在控制台应用程序中反序列化一些 XML。我只关心一些数据,所以我创建了一个只包含我需要的字段的类。程序运行,但我反序列化到的 PetFinderPetRecord 具有所有空成员(所有字符串为空,所有整数为 0)。

这是 XML:

<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd">
<header>
<version>0.1</version>
<timestamp>2014-10-23T04:12:37Z</timestamp>
<status>
<code>100</code>
<message/>
</status>
</header>
<pet>
<id>29165893</id>
<shelterId>VA72</shelterId>
<shelterPetId/>
<name>Buckeye and Hawkeye</name>
<animal>Cat</animal>
<breeds>
<breed>Domestic Short Hair-black</breed>
</breeds>
<mix>no</mix>
<age>Baby</age>
<sex>M</sex>
<size>M</size>
<options>
<option>hasShots</option>
<option>altered</option>
<option>housetrained</option>
</options>
<description>
<![CDATA[
Buckeye and Hawkeye are about 6 months old as of 5/6/14. Buckeye and his brother, Hawkeye, are very bonded and hope to find a home together. They are very playful and love to have their chin scratched. They get along very well with other cats and are curious and lovable. They will make a wonderful addition to your family. Please email jleach1234@aol.com for more information.
]]>
</description>
<lastUpdate>2014-05-07T21:30:42Z</lastUpdate>
<status>A</status>
<media>
<photos>
<photo id="1" size="pnt">
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=60&-pnt.jpg
</photo>
<photo id="1" size="fpm">
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=95&-fpm.jpg
</photo>
<photo id="1" size="x">
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=500&-x.jpg
</photo>
<photo id="1" size="pn">
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=300&-pn.jpg
</photo>
<photo id="1" size="t">
http://photos.petfinder.com/photos/pets/29165893/1/?bust=1399498241&width=50&-t.jpg
</photo>
<photo id="2" size="pnt">
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=60&-pnt.jpg
</photo>
<photo id="2" size="fpm">
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=95&-fpm.jpg
</photo>
<photo id="2" size="x">
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=500&-x.jpg
</photo>
<photo id="2" size="pn">
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=300&-pn.jpg
</photo>
<photo id="2" size="t">
http://photos.petfinder.com/photos/pets/29165893/2/?bust=1399498241&width=50&-t.jpg
</photo>
</photos>
</media>
<contact>
<address1>PO Box 7040</address1>
<address2/>
<city>Fairfax Station</city>
<state>VA</state>
<zip>22039</zip>
<phone>(703) 940-9183</phone>
<fax/>
<email>Jleach1234@aol.com</email>
</contact>
</pet>
</petfinder>

这是控制台代码:

public class Class1
{
    static void Main(string[] args)
    {
        string URL = "http://api.petfinder.com/pet.getRandom";
        string urlParameters = "?key=myprivatekey&id=ID123&status=A&format=xml&output=full";

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(URL);

        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/xml"));

        HttpResponseMessage response = client.GetAsync(urlParameters).Result;
        if (response.IsSuccessStatusCode)
        {
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "petfinder";
            xRoot.IsNullable = true;
            XmlSerializer serializer = new XmlSerializer(typeof(PetFinderPetRecord), xRoot);

            PetFinderPetRecord record = null;

            using (Stream stream = response.Content.ReadAsStreamAsync().Result)
            {
                record = (PetFinderPetRecord)serializer.Deserialize(stream); // <-- has empty members
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }
    }
}

这是我要反序列化的类:

[Serializable()]
public class PetFinderPetRecord
{
    [XmlElement("id")]
    public int id { get; set; }

    [XmlElement("shelterId")]
    public int shelterId { get; set; }

    [XmlElement("shelterPetId")]
    public int shelterPetId { get; set; }

    [XmlElement("name")]
    public string name { get; set; }

    [XmlElement("animal")]
    public string animal { get; set; }

    [XmlElement("mix")]
    public string mix { get; set; }

    [XmlElement("age")]
    public string age { get; set; }

    [XmlElement("sex")]
    public string sex { get; set; }

    [XmlElement("size")]
    public string size { get; set; }

    [XmlElement("description")]
    public string description { get; set; }

    [XmlElement("lastupdate")]
    public DateTime lastupdate { get; set; }

    [XmlElement("status")]
    public string status;

    public PetFinderPetRecord()
    {

    }
}

如果有人能告诉我我缺少什么或我做错了什么,我将不胜感激。提前谢谢你。

【问题讨论】:

  • 请编辑您的代码示例,使其成为能够可靠重现问题的良好、简洁但完整的代码示例 (stackoverflow.com/help/mcve)
  • 这是我可以提供的重现问题的最少代码量。为了完整起见,我提供了所有的 XML 和我想要反序列化的类。
  • 这实际上不可能是可以重现问题的最少代码量。因此,如果您不能提供更少的内容,那么学习如何修剪代码示例对您来说是一个很好的练习。此外,几乎可以肯定您的错误可以在不实际查询 Web 服务器的情况下被演示,因此在这方面,这里有 更多 代码而不是必要的。同样,请参阅我引用的关于如何提供“MCVE”(用 SO 行话)的链接。

标签: c# asp.net xml xml-deserialization


【解决方案1】:

不确定这是否是唯一的问题,但在这行代码上:

            HttpResponseMessage response = client.GetAsync(urlParameters).Result;

你应该等待电话:

            HttpResponseMessage response = await client.GetAsync(urlParameters).Result;

否则你的 if 语句可能会在服务器响应之前执行

注意:为此,您还需要在方法声明中添加 async 关键字

static void async Main(string[] args)

希望对你有帮助

【讨论】:

  • 感谢您的建议,我已经尝试过了。我创建了一个名为getData() 的新方法,而不是将async 放在Main 上(因为我收到一条错误消息,指出async 不能用于入口点)。我还做了您在HttpResponseMessage 上建议的其他更改。现在,当我调试时,当我越过那条线 (F10) 时,执行就会停止。我还将代码包装在 try catch 块中,但没有抛出异常。您还有其他建议吗?
  • 我已更新getData() 以返回Task,现在我从Main() 调用它:get().Wait() 该方法现在返回,但对象仍然是空的。有没有人有任何进一步的建议?
  • 你从服务器得到什么响应代码?我将您的代码简化为 xml 反序列化步骤,并让它尝试反序列化您在问题中提供的 xml 文件,当它到达第 38 行第 68 个字符(URL 中的 -)时,它引发了 InvalidOperation 异常
  • 感谢您继续与我一起调查此事。 StatusCode 是 200,ReasonPhrase 是“OK”,IsSuccessStatusCodetrue
  • 我通过验证器 (w3schools.com/xml/xml_validator.asp) 运行了 XML,它显示“第 38 行第 74 列的错误:EntityRef:期待 ';'”。看起来我需要在尝试反序列化 XML 之前对其进行操作。
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多