xml序列化与反序列化
作者:互联网
说明:.net 后台开发环境支持
类库引用:using
System.Xml.Serialization;
假设当前存在A和B,A中包含B,如下:
public class A
{
string code;
string name;
list<B> blist;
}
public class B
{
string coursename;
string source;
}
xml序列化
List<a> alist = new List<a>();
XmlDocument xmldoc = new XmlDocument();
//---具体给A赋值的逻辑不再赘述,现假设A中有值存在
using(
StringWriter sw =
new
StringWriter()
)
{
XmlSerializer serializer =
new
XmlSerializer(
typeof
(alist));//或者
XmlSerializer serializer =
new
XmlSerializer(
alist.GetType);
serializer .Serializer (sw,alist );
xmldoc.LoadXml(sw.ToString());//将字符串转为xml编码格式的文档
var loaddata = System.Text.Encoding.Default.GetBytes(xmldoc.OuterXml);//将xml格式的文件转为byte类型,注意类型的使用,不然这种方式存储的流会在解释时候解析错误。
} //执行完毕记得关闭writer
xml反序列化
//xml已知具体路径解析
FileStream file =
new
FileStream(
@"D://aaa/info.xml"
, FileMode.Open, FileAccess.Read);
XmlSerializer xmlSearializer =
new
XmlSerializer(
typeof
(List<a>));
alist
= (A)xmlSearializer.Deserialize(file);
file.Close();
//xml已知为文件流stream形式
假设为前台上传的文件,以form形式传参,传到后台将文件格式为IFormFile类型file(file为前台文件上传到后台的参数)
public string desxml(IFormFile file)
{
List<a> alist = new List<a>();
Stream filestream = file.OpenReadStream();
XmlSerializer xmlSearializer =
new
XmlSerializer(
typeof
(List<a>));
using(StreamReader read = new StreamReader (filestream ,Encoding.Default))
{
try{
alist =xmlSearializer .Deserialize(read ) as List<a>;
}
catch{}
}
}
标签:xml,List,alist,file,new,XmlSerializer,序列化 来源: https://www.cnblogs.com/zwbsoft/p/15937643.html