Converting xml to Object c #

If I have xml forms

<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 read xml directly and create Detail objects.

+2


a source to share


5 answers


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 ...

+4


a source


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.

+2


a source


You can also use DataContractSerializer

.

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

+1


a source


  • 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);  
    }
    
          

0


a source


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

}

      

0


a source







All Articles