简体   繁体   中英

XML deserialization attempt yields empty object

I am trying to deserialize some XML in a console app. I only care about some of the data, so I created a class with just the fields that I need. The program runs, but the PetFinderPetRecord that I deserialize to has all empty members (all strings are null and all ints are 0).

Here is the 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>

Here is the console code:

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);
        }
    }
}

And here is the class I'm trying to deserialize to:

[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()
    {

    }
}

If someone could show me what I'm missing or what I'm doing wrong, I would greatly appreciate it. Thank you in advance.

not sure if this is the only problem, but on this line of code:

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

you should await the call:

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

otherwise your if statement could execute before there is a server response

note: to do this, you also need to add the async keyword to your method declaration

static void async Main(string[] args)

I hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM