Saturday, 4 April 2015

XMLserialize object of list and string



So i need to xml serialize a generic list of objects where the object consists of another list and a string.


This is what i get now



<?xml version="1.0" encoding="UTF-8"?>

-<ArrayOfRecept xmlns:xsd="http://ift.tt/tphNwY" xmlns:xsi="http://ift.tt/ra1lAU">


-<Recept>
<Namn>Nomnom</Namn>
</Recept>

-<Recept>
<Namn>Ännu mer nomnom</Namn>
</Recept>

</ArrayOfRecept>


Here only the string value is serialized and not my List


This is my object that i want to serialize



public class Recept
{

private ListHanterare<string> ingredienser;
private string namn;

public Recept()
{
ingredienser = new ListHanterare<string>();
}
public ListHanterare<string> Ingredienser
{
get { return ingredienser; }

}

public string Namn
{
get { return namn; }
set { namn = value; }
}

}


So I will have a list of Recept that i want to xml serialize and I want the xml to show both "Namn" and the "Ingredienser"-list.


This is my serializer



class XMLSerial
{
public static bool Serialize<T>(T obj, string filePath)
{
bool bok = true;

XmlSerializer serializer = new XmlSerializer(typeof(T));
TextWriter writer = new StreamWriter(filePath);
try
{
serializer.Serialize(writer, obj);
}
catch
{
bok = false;
}
finally
{
if (writer != null)

writer.Close();
}

return bok;
}

}


This is inside the ListHanterare class where I pass the object to the serializer



public bool XMLSerialize(string filePath){
return XMLSerial.Serialize<List<T>>(lista, filePath);

No comments:

Post a Comment