C#序列化与反序列化Xml,利用范型做通用化处理
public class yzzSerialize
{
private yzzSerialize()
{ }
private static yzzCache cache = new yzzCache();
public static T GetfromXml<T>(string xmlpath, T t)
{
using (FileStream fs = new FileStream(xmlpath, FileMode.Open, FileAccess.Read))
{
Type type = typeof(T);
XmlSerializer xs = cache[type.FullName] as XmlSerializer;
if (xs == null)
{
xs = new XmlSerializer(type);
cache[type.FullName] = xs;
}
t = (T)xs.Deserialize(fs);
fs.Close();
return t;
}
}
public static void SetToXml<T>(string xmlpath, T t)
{
if (t == null)
return;
using (FileStream fs = new FileStream(xmlpath, FileMode.Create, FileAccess.Write))
{
Type type = typeof(T);
XmlSerializer xs = cache[type.FullName] as XmlSerializer;
if (xs == null)
{
xs = new XmlSerializer(type);
cache[type.FullName] = xs;
}
xs.Serialize(fs, t);
t = default(T);
fs.Close();
}
}
}
相关文档:
有人会问,DTD和Schema都是对XML文档的一种约束,为什么不就选其中之一,而又有Schema呢。因为DTD安全度太低了,也就是说它的约束定义能力不足,无法对XML实例文档做出更细致的语义限制。其实细心的人会发现,在DTD中,只有一个数据类型,就是PCDATA(用在元素中)和CDATA(用在属性中),在里面写日期也行,数字还行,字符 ......
C#
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Config/User_yhlx_Jb.xml"));
DataView dv = ds.Tables[0].DefaultView;
//dv.RowFilter = "State=0";
this.DropDownList1.DataSource = dv;
this.DropDownList1.DataTextField = "text";
this ......
原先一直用BinaryFormatter来序列化挺好,可是最近发现在WinCE下是没有办法进行BinaryFormatter操作,很不爽,只能改成了BinaryWriter和BinaryReader来读写,突然想到能不能用XML来序列化?于是在网上查了些资料便写了些实践性代码,做些记录,避免以后忘记。
序列化对象
public class People
......
/**
* ftp上传文件JavaBean
* @author Administrator
*
*/
public class FtpBean {
//ftp服务地址
private String ftpUrl="";
//ftp用户名
private String userName="";
//ftp密码
private String passWord="";
public String getF ......
范例如下:
var xml:XML=
<body>
text1
<bar>barText1</bar>
& ......