这两天公司需要将订单相关信息生成xml文件,用来做报关信息。
所以就分享这种生成方式吧。
本示例采用XmlSerializer生成。
大概思路:1、根据xml文件的格式对应写出相应的实体类;2、数据填充;3、进行xml序列化;4、读取流并保存为xml文件
好了,下面会给出一个完成的教程
1、这是一个xml文件格式,xmlRoot 为ClassA,此为根节点,此外有两个子节点 ;
<ClassA>
<Teacher>
<Name>xxxxx</Name>
<Age>xxxxxx</Age>
</OrderHead>
<Students>
<Name>1</itemNo>
<Age>2001003</goodsNo>
<Students>
<Students>
<Name>1</itemNo>
<Age>2001003</goodsNo>
</Students>
<ClassA>
2、设计实体类public Class ClassA
{
public Teacher Teacher{get;set;}
[XmlElement]
pubilc Students[] Students{get;sett;}
}
pubilc Class Teacher
{
pubilc string Name{get;set;}
pubilc string Age{get;set;}
}
pubilc Class Students
{
pubilc string Name{get;set;}
pubilc string Age{get;set;}
}
3、对实体进行数据填充后,即进行xml序列化并保存文件
if (!Directory.Exists(path))//path 即保存文件的目录
{
Directory.CreateDirectory(path);
}
string fileName = string.Format("{0}-{1}.xml"
, DateTime.Now.ToString("yyyyMMddHHmmssff"), "xxx"//定义文件名
);
string xml = "";
using (MemoryStream ms = new MemoryStream())
{
//创建XML命名空间
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
XmlSerializer serializer = new XmlSerializer(typeof(ClassA));
ns.Add("", "");//去除命名空间
serializer.Serialize(ms, request, ns);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
xml = sr.ReadToEnd().Replace("_x003A_", ":");
if (!string.IsNullOrEmpty(fileName) && !string.IsNullOrEmpty(xml))
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
UTF8Encoding utF8Encoding = new UTF8Encoding(true);
File.WriteAllText(Path.Combine(path, fileName), xml, (Encoding)utF8Encoding);//保存文件成功
}
}
4、获取到文件名和路径后即可返回前台进行下载。至此大功告成。。。。。