I' trying to set list data into xml format. I have a complex objects
class user Info that is contain a list of another class object
[Serializable]
class UserInfo : Address
{
[XmlElement("Firstname")]
public String firstname { get; set; }
[XmlElement("Surname")]
public String surname { get; set; }
[XmlArray("Addresses")]
// [XmlArrayItem("Address",typeof(Address))]
public List<Address> addressesL { get; set;}
}
Address class has only one field of string
class Address
{
[XmlElement("Address")]
public String saddress { get; set; }
}
here is the main
static void Main(string[] args)
{
UserInfo user = new UserInfo();
Address adres = new Address();
List<Address> adresl = new List<Address>();
List<UserInfo> userlist = new List<UserInfo>();
user.firstname = "Mustafa";
user.surname = "Alqanbar";
adres.saddress = "Saudi Arabia";
adresl.Add(adres);
adres = new Address();
adres.saddress = "Australia";
adresl.Add(adres);
user.addressesL = adresl;
userlist.Add(user);
for (int i = 0; i < userlist.Count; i++)
{
Console.Write("{0} {1} ",userlist[i].firstname, userlist[i].surname);
for (int j = 0; j < userlist[i].addressesL.Count; j++)
{
Console.Write("{0} ",userlist[i].addressesL[j].saddress);
}
Console.WriteLine();
}
XmlSerializer ser = new XmlSerializer((typeof(List<UserInfo>)));
// XmlSerializer deser = XmlSerializer.FromTypes(new[] { (typeof(List<UserInfo>)) })[0];
using (TextWriter writer = new StreamWriter(@"c:\x.xml"))
{
ser.Serialize(writer, user);
}
Console.ReadKey();
}
I read some posts in stack overflow, but I couldn't sort my problem out.
答案 0 :(得分:3)
To my understanding, a class that is to be written and read by an XmlSerializer
must be declared public
in its namespace; at least in this example it is the case.
答案 1 :(得分:0)
If i change the string XmlSerializer ser = new XmlSerializer((typeof(List<UserInfo>)));
to the XmlSerializer ser = new XmlSerializer(typeof(UserInfo));
then it works for me.
The classes should be declared as public