0

我正在尝试反序列化此结构的 xml 文件,但是当我调用此方法时

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

没有一个 PricingQuote 子元素通过

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

1 回答 1

1

您需要确保您的类定义与传入的 XML 匹配。下面的那些这样做,反序列化按预期工作。

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);
        }
    }
}
于 2012-09-26T19:11:12.800 回答