user1701232
user1701232

Reputation: 1

Deserialize child elements using xmlserializer

I'm trying to deserialize a xml file of this strucuture, but when I call this method

XmlSerializer(responseType).Deserialize(new MemoryStream(responseData))

none of the PricingQuote Child elements come through

<Pricing>
 <Code>Success</Code>
 <PricingQuotes> 
  <PricingQuote>
    <ProductName>Conforming 30 Year Fixed</ProductName>
  </PricingQuote>
  <PricingQuote>
    <ProductName>Conforming 20 Year Fixed</ProductName>
  </PricingQuote>
 </PricingQuotes> 
</Pricing>

Upvotes: 0

Views: 2355

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87238

You need to make sure that your class definitions match the incoming XML. The ones below do that, and the deserialization works as expected.

public class StackOverflow_12608671
{
    const string XML = @"<Pricing> 
                            <Code>Success</Code> 
                            <PricingQuotes>  
                                <PricingQuote> 
                                    <ProductName>Conforming 30 Year Fixed</ProductName> 
                                </PricingQuote> 
                                <PricingQuote> 
                                    <ProductName>Conforming 20 Year Fixed</ProductName> 
                                </PricingQuote> 
                            </PricingQuotes>  
                        </Pricing> ";

    public class Pricing
    {
        public string Code { get; set; }
        public List<PricingQuote> PricingQuotes { get; set; }
    }
    public class PricingQuote
    {
        public string ProductName { get; set; }
    }
    public static void Test()
    {
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
        XmlSerializer xs = new XmlSerializer(typeof(Pricing));
        Pricing p = (Pricing)xs.Deserialize(ms);
        foreach (var q in p.PricingQuotes)
        {
            Console.WriteLine(q.ProductName);
        }
    }
}

Upvotes: 1

Related Questions