I have following xml which I want to Deserialize to an object.
<result>
<reporttype>2</reporttype>
<items>
<item>
<sku>0B0005</sku>
<style>0B0005.DAK.GREY</style>
<reason>Barcode cannot be moved to different SKUs</reason>
</item>
<item>
<sku>0B0006</sku>
<style>0B0006.DAK.GREY</style>
<reason>Barcode cannot be moved to different SKUs</reason>
</item>
</items>
</result>
But following code does not populate the item list, Can someone point me out what I am doing wrong here
string inputString = @"<result><reporttype>2</reporttype><items><item><sku>0B0005</sku><style>0B0005.DAK.GREY</style><reason>Barcode cannot be moved to different SKUs</reason></item><item><sku>0B0005</sku><style>0B0005.DAK.GREY</style><reason>Barcode cannot be moved to different SKUs</reason></item></items></result>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(inputString);
XmlSerializer serializer = new XmlSerializer(typeof(Result));
StringReader rdr = new StringReader(doc.InnerXml);
Result resultingMessage = (Result)serializer.Deserialize(rdr);
public enum ReportType {
[XmlEnum("0")]
InternalErrorReport,
[XmlEnum("1")]
ErrorReport,
[XmlEnum("2")]
InternalSuccessReport
}
[XmlRoot(ElementName = "result")]
public class Result {
[XmlElement(ElementName = "reporttype")]
public ReportType reportType { get; set; }
[XmlElement(ElementName = "items")]
public List<Item> items = new List<Item>();
public string error { get; set; }
public class Item {
[XmlElement(ElementName = "sku")]
string sku { get; set; }
[XmlElement(ElementName = "style")]
string style { get; set; }
[XmlElement(ElementName = "reason")]
string reason { get; set; }
}
}
Or is there a better way to do this?
Variable need to be public.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Result));
StringReader rdr = new StringReader(xml);
Result resultingMessage = (Result)serializer.Deserialize(rdr);
}
}
public enum ReportType
{
[XmlEnum("0")]
InternalErrorReport,
[XmlEnum("1")]
ErrorReport,
[XmlEnum("2")]
InternalSuccessReport
}
[XmlRoot(ElementName = "result")]
public class Result
{
[XmlElement(ElementName = "reporttype")]
public ReportType reportType { get; set; }
public Items items { get; set; }
public string error { get; set; }
}
[XmlRoot("items")]
public class Items
{
[XmlElement(ElementName = "item")]
public List<Item> items = new List<Item>();
}
[XmlRoot("item")]
public class Item
{
[XmlElement(ElementName = "sku")]
public string sku { get; set; }
[XmlElement(ElementName = "style")]
public string style { get; set; }
[XmlElement(ElementName = "reason")]
public string reason { get; set; }
}
}