How to Deserialize Xml to Object

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
[XmlElement("Step")]
public List<Step> Steps { get; set; }
}

public class Step
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Desc")]
public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
<Step>
<Name>Name1</Name>
<Desc>Desc1</Desc>
</Step>
<Step>
<Name>Name2</Name>
<Desc>Desc2</Desc>
</Step>
</StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream
and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
StepList result = (StepList) serializer.Deserialize(fileStream);
}

How do I deserialize XML that uses a key into an object

Try following :

    [XmlRoot("properties")]
public class LogProperties
{

[XmlElement("property")]
public List<LogProperty> property { get; set; }

}
[XmlRoot("property")]
public class LogProperty
{
[XmlAttribute("key")]
public string key { get; set; }
[XmlText]
public string value { get; set; }
}

Deserialize XML into object with dynamic child elements

I've managed to resolve this using a dynamic type when deserializing.
When I deserialize ValuesRead, it is a defined as a dynamic type.

When deserialized, it turns into an XmlNode and from there I iterate over the node use the Name and InnerText values to read all the data.

Deserialize xml file with mixed types

Try following xml linq :

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication100
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);

Article article = doc.Descendants("Article").Select(x => new Article() { Stories = x.Elements("Story").Select(y => Story.ParseStory(y)).ToList() }).FirstOrDefault();

}


}
public class InputXmlModel
{
public List<Article> Articles { get; set; }

}


public class Article
{
public List<Story> Stories { get; set; }
}

public class Story
{
public string Title { get; set; }
public string Author { get; set; }
public string Lead { get; set; }
public List<Item> Items { get; set; }
public List<StoryPicture> Pictures { get; set; }

enum State
{
DEFAULT,
SUBTITLE,

}
public static Story ParseStory(XElement xStory)
{
Story story = new Story();
State state = State.DEFAULT;
Item newItem = null;
StoryPicture newPicture = null;
foreach (XElement child in xStory.Elements())
{
switch(state)
{
case State.DEFAULT :
switch (child.Name.LocalName)
{
case "Title" :
story.Title = (string)child;
break;
case "Author":
story.Author = (string)child;
break;
case "Lead":
story.Lead = (string)child;
break;
case "Subtitle":
newItem = new Item();
if (story.Items == null) story.Items = new List<Item>();
story.Items.Add(newItem);

state = State.SUBTITLE;
break;
case "Picture":
newPicture = new StoryPicture()
{
ImageHref = (string)child.Element("Image").Attribute("href"),
Credit = (string)child.Element("Credit"),
Description = (string)child.Element("Description")
};
if (story.Pictures == null) story.Pictures = new List<StoryPicture>();
story.Pictures.Add(newPicture);

break;
default:
Console.WriteLine("Error");
Console.ReadLine();
break;
}
break;


case State.SUBTITLE :
switch (child.Name.LocalName)
{
case "Body" :
newItem.ItemType = "SubTitle";
newItem.ItemText = (string)child;
break;

case "Subtitle":
newItem = new Item();
if (story.Items == null) story.Items = new List<Item>();
story.Items.Add(newItem);
break;

default:
Console.WriteLine("Error");
Console.ReadLine();
break;
}

break;
}
}

return story;
}
}

public class StoryPicture
{
public string ImageHref { get; set; }
public string Credit { get; set; }
public string Description { get; set; }
}
public class Item
{
public string ItemType { get; set; } // Possible: Body or Subtitle
public string ItemText { get; set; }
}



}

Deserialize XML object. Fields are not initialized

You have a few issues with your objects. You are trying to get attributes in place of elements and your arrays are not arrays, they are merely complex elements. Below is a working example that matches your xml schema

class Program
{
static void Main(string[] args)
{
string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<getInvoiceReply>
<invoiceID value=""944659502""/>
<invFastener>
<fastenerID value=""""/>
<fastenerName value=""""/>
<fastenerCount value=""""/>
<fastenerProperty>
<propID value=""""/>
<propName value=""""/>
<propValue value=""""/>
</fastenerProperty>
</invFastener>
</getInvoiceReply>";



var serializer = new XmlSerializer(typeof(InvoiceReply));
var i = (InvoiceReply)serializer.Deserialize(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)));

Console.ReadKey();
}
}

//Generic class for getting value attribute
public class ValueElement
{
[XmlAttribute("value")]
public string Value { get; set; }
}

[XmlRoot("getInvoiceReply")]
public class InvoiceReply
{
[XmlElement("invoiceID")]
public ValueElement InvoiceId { get; set; } //This is a value element

[XmlElement("invFastener")]
public List<InvFastener> InvFastener { get; set; } //This is an element, not an array
}

public class InvFastener
{
[XmlElement("fastenerID")]
public ValueElement FastenerID { get; set; }//This is a value element

[XmlElement("fastenerName")]
public ValueElement FastenerName { get; set; }//This is a value element

[XmlElement("fastenerCount")]
public ValueElement FastenerCount { get; set; }//This is a value element

[XmlElement("fastenerProperty")]
public List<FastenerProperty> FastenerProperties { get; set; } //This is an element, not an array
}

public class FastenerProperty
{
[XmlElement("propID")]
public ValueElement PropId { get; set; }//This is a value element

[XmlElement("propName")]
public ValueElement PropName { get; set; }//This is a value element

[XmlElement("propValue")]
public ValueElement PropValue { get; set; }//This is a value element
}

Deserialize XML to object with xmlns namespace problem

You can use an XmlTextReader to ignore the namespaces before you deserialize your result.
Also, your ArrayOfThemes class should probably have an array of themes unless you only ever expect one. Below example works for deserializing that xml.

class Program
{
static void Main(string[] args)
{
var xml = @"<ArrayOfThemes xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""https://brickset.com/api/"">
<themes>
<theme>4 Juniors</theme>
<setCount>24</setCount>
<subthemeCount>5</subthemeCount>
<yearFrom>2003</yearFrom>
<yearTo>2004</yearTo>
</themes>
</ArrayOfThemes>";
var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
var reader = new XmlTextReader(ms) {Namespaces = false};
var serializer = new XmlSerializer(typeof(ArrayOfThemes));

var result = (ArrayOfThemes) serializer.Deserialize(reader);
}
}

public class Themes
{
[XmlElement("theme")]
public string Theme { get; set; }
[XmlElement("setCount")]
public string SetCount { get; set; }
[XmlElement("subthemeCount")]

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

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

public string YearTo { get; set; }
}

[Serializable, XmlRoot("ArrayOfThemes")]
public class ArrayOfThemes
{
[XmlElement("themes")]
public Themes[] Themes { get; set; }
}


Related Topics



Leave a reply



Submit