2

How to serialize & deserialize below xml file using C#. I have created serializable class for this xml.

below some code to deserialize this xml, the list is able to get only single value.

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<CSVFile>
<string>ff</string>
<string>gg</string>
<string>jj</string>
</CSVFile> 
</Configuration>


[Serializable, XmlRoot("Configuration"), XmlType("Configuration")]
public class Configuration
{
    public Configuration()
    {
        CSVFile = new List<string>();
    }

    [XmlElement("CSVFile")]
    public List<string> CSVFile { get; set; }
}

public class Mytutorial
{
    string configFilePath = "above xml file path"

    XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
    FileStream xmlFile = new FileStream(configFilePath, FileMode.Open);
    Configuration con = (Configuration)serializer.Deserialize(xmlFile);
 }
AMIT SHELKE
  • 501
  • 3
  • 12
  • 34
  • refer to this question: http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document – Marco Aug 19 '13 at 10:06
  • possible duplicate of [Generate C# class from XML](http://stackoverflow.com/questions/4203540/generate-c-sharp-class-from-xml) – xanatos Aug 19 '13 at 10:06
  • Very interesting CSV file. Where are columns and where are rows? Is each `string` a line? – Dariusz Aug 19 '13 at 10:12

2 Answers2

4

Just change your class as below, it will work

public class Configuration
{
    [XmlArray("CSVFile")]
    public List<string> CSVFile { get; set; }
}
I4V
  • 34,891
  • 6
  • 67
  • 79
4

Your XML definition does not match your models.

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
  <CSVFile>
    <csvstrings>ff</csvstrings>
    <csvstrings>gg</csvstrings>
    <csvstrings>jj</csvstrings>
  </CSVFile> 
</Configuration>

It requires the following models:

Configuration
CSVFile

So, your implementation should be:

[Serializable]
public class CSVFile
{
    [XmlElement("csvstrings")]
    public List<string> csvstrings { get; set; }

    public CSVFile()
    {

    }
}

[Serializable, XmlRoot("Configuration"), XmlType("Configuration")]
public class Configuration
{
    public Configuration()
    {

    }

    [XmlElement("CSVFile")]
    public CSVFile csvs { get; set; }
}

public class Mytutorial
{
    string configFilePath = "above xml file path"

    XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
    FileStream xmlFile = new FileStream(configFilePath, FileMode.Open);
    Configuration con = (Configuration)serializer.Deserialize(xmlFile);
}
Jefraim
  • 193
  • 9