Converting xml to Object c #
have a look at the XmlSerializer - this creates / parses xml from your object form (so your property names must match the attribute / element names in the xml).
If you need more control, you will need to work with the new Linq to XML API
XSD.exe can generate a class file for you based on an XSD or XML file, but if you click on the XML file, you need a pretty representative one (with multiple elements wherever there may be multiple elements), otherwise you will need to tweak a few things. It's a good start though ...
a source to share
Linq to XML is pretty good for this.
var details = from detail in document.Descendants("Detail")
select new Detail { Name1 = detail.Element("Name1").Value, Name2 = detail.Element("Name2").Value };
(This assumes you have defined a type called Detail; you can very easily omit Detail
and get an anonymous type.)
This code will result in a IEnumarable<Detail>
(or anonymous type) that you can execute on your objects.
a source to share
You can also use DataContractSerializer
.
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
a source to share
- You need to use
XSD.exe
to generate C # class from XML file. See this post for details . -
Use
XmlSerializer
to deserialize a class:XmlSerializer serializer = new XmlSerializer(typeof(Details)); using (var fs = new FileStream(filename, FileMode.Open)) { XmlReader reader = XmlReader.Create(fs); var result = (Details)serializer.Deserialize(reader); }
a source to share
Use this code:
DetailList dl;
XmlSerializer xmls = new XmlSerializer(typeof(List<DetailList>))
using (Stream fs = new FileStream(@"C:\path\to\file.xml", FileMode.Open))
dl = (DetailList)xmls.Deserialize(fs);
Make sure you populate your classes with the correct attributes. Use
using System.Xml.Serialization;
// ...
[Serializable]
public class Detail
{
[XmlElement]
public string Name1 { get; set; }
[XmlElement]
public string Name2 { get; set; }
// REQUIRED: a parameterless constructor for XmlSerializer (can be private)
private Detail(){}
public Detail(string name1, string name2)
{
Name1 = name1;
Name2 = name2;
}
}
[Serializable, XmlRoot("Details")]
public class DetailList : List<Detail>
{
}
a source to share