tags:

views:

86

answers:

5

If i have an xml of the form

<Details>
<Detail>
<Name1>Value1</Name1>
<Name2>Value2</Name2>
</Detail>
...
</Details>

And i define a class in my c# code for Detail and provide setters/getters for Name1, Name2 etc is there an api to directly read the xml and create Detail objects.

+4  A: 

look at the XmlSerializer - this creates / parses xml from the shape of your object (so your property names need to match the attribute / element names in the xml).

If you need more control, you'll want to work with the newer Linq to XML API

XSD.exe can produce a class file for you based on an XSD or XML file, but if you aim it an an XML file, you'll need a pretty representative one (with multiple elements wherever there can be multiple elements), otherwise you'll need to tweak a few things. It's a good start though...

Rob Fonseca-Ensor
This is exactly how I end up doing XML -> C#, especially if you've already defined a class for it.
Matthew Doyle
A: 
  1. You'll need to use XSD.exe to create a C# class from the xml file - see this post for details.
  2. Use XmlSerialize to deserialize the class:

    XmlSerializer s = new XmlSerializer(typeof(Details));
    using(FileStream fs = new FileStream(filename, FileMode.Open))
    {
    XmlReader reader = XmlReader.Create(fs);
    var result = (Details)serializer.Deserialize(reader);
    }

Dror Helper
+2  A: 

Linq to XML is pretty nice 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 could very well omit the Detail and obtain an anonymous type.)

This code will result in an IEnumarable<Detail> (or anon. type) that you can iterate over for your objects.

Anthony Pegram
A: 

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 have populated 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>
{

}
Callum Rogers
Don't you mean `new XmlSerializer(typeof(Deatil))`
Rob Fonseca-Ensor
typos - now corrected
Callum Rogers
+1  A: 

You could also use the DataContractSerializer.

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx

Damian Powell