如何将列表转换为xml字符串,将xml转换为列表 [英] how to convert list to xml string and xml to list
本文介绍了如何将列表转换为xml字符串,将xml转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class FeePlanGenerate
{
public List<FeePlan> FeePlanList { get; set; }
public List<FeeComponent> FeeComponentList { get; set; }
public string StudentName { get; set;}
public string StudentAddress { get; set; }
public string CurriculumName { get; set; }
public string CourseName { get; set; }
public string BCNumber { get; set; }
public Nullable< DateTime> AddmissionDate { get; set; }
public string AddmissionOfficer{ get; set; }
public string Contant1 { get; set; }
public string Contant2 { get; set; }
public string AdmissionCode { get; set; }
public Nullable< decimal> TotalInvoiceAmount { get; set; }
public Nullable<decimal> TotalPayableFee { get; set; }
public string ArrayOfFeePlanGenerate { get; set; }
}
推荐答案
嗨Ahsan70,
Hi Ahsan70,
>>如何将列表转换为xml字符串,将xml转换为列表
>>how to convert list to xml string and xml to list
我做了一个简单的演示为此,请参考下面的内容。
I make a simple demo for this purpose, please refer to it as below.
创建一个用于序列化和反序列化的类:
Create a class used for serialization and deserialization:
// serialization and deserialization
public class XmlUtil
{
#region deserialization
// deserialization
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
// deserialization
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
#region serialization
// serialization
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//Serialized object
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
}
然后我简化了您提供测试的课程:
Then I simplified the class that you provided for test as this:
public class Student
{
public string Name { set; get; }
public int Age { set; get; }
}
然后达到如下目的:
string xml;
private void button1_Click(object sender, EventArgs e)
{
//Generate a List object for testing
List<Student> list1 = new List<Student>(3);
list1.Add(new Student() { Name = "James", Age = 33 });
list1.Add(new Student() { Name = "Kobe", Age = 39 });
//serialization
xml = XmlUtil.Serializer(typeof(List<Student>), list1);
Console.Write(xml);
}
private void button2_Click(object sender, EventArgs e)
{
//deserialization
List<Student> list2 = XmlUtil.Deserialize(typeof(List<Student>), xml) as List<Student>;
foreach (Student stu in list2)
{
Console.WriteLine(stu.Name + "," + stu.Age.ToString());
}
}
结果:
希望这会有所帮助!
问候,
Stanly
这篇关于如何将列表转换为xml字符串,将xml转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文