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();
}
}
}
相关文档:
XML Schema import 元素
定义和用法
import 元素用于向一个文档添加带有不同目标命名空间的多个 schema。
元素信息
出现次数
无限制
父元素
schema
内容
annotation
语法
<import
id=ID
namespace=anyURI
schemaLocation=anyURI
any attributes
>
(annotation?)
< ......
范例如下:
var xml:XML=
<body>
text1
<bar>barText1</bar>
& ......
2)如何创建一个xml文档
由于xml实质也只是一个文本文件,所以最简单你可以直接使用System.IO下的类生成一个文件,并存储成xml文件,当然,你需要手动保证该文件形式良好,比如必须有根元素、必须有关闭标签、必须正确嵌套等等。
如果你懒得自己去想文件的形式,可以使用System.Xml下的类。
Code
Xml ......