AMIT SHELKE
AMIT SHELKE

Reputation: 533

serialize & deserialize with property as list<string> xml file using C#

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

Upvotes: 2

Views: 17489

Answers (2)

Jefraim
Jefraim

Reputation: 193

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

Upvotes: 4

I4V
I4V

Reputation: 35353

Just change your class as below, it will work

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

Upvotes: 4

Related Questions