using System;
public class User
{
public string id;
public string pass;
}
public class Test
{
public static void Main()
{
string target = @"D:\test.xml";
List<User> user = new List<User>();
acclist.LoadXml(target);
// your code goes here
}
}
public class ListEx<Type> : System.Collections.Generic.List<Type>
{
// データ保存用のジェネリッククラス
public class Xmldata<Type>
{
public Type[] data;
}
// Xmlからコレクションを復元
public void LoadXml(string path)
{
// コレクションをクリア
this.Clear();
Xmldata<Type> buff = null;
try
{
System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(Xmldata<Type>));
xdoc.PreserveWhitespace = true;
xdoc.Load(path);
System.Xml.XmlNodeReader xnr = new System.Xml.XmlNodeReader(xdoc.DocumentElement);
buff = (Xmldata<Type>)xml.Deserialize(xnr);
for (int i = 0; i < buff.data.Length; i++)
{
this.Add(buff.data[i]);
}
}
#region 例外処理
catch
{
}
#endregion
return;
}
// これでXmlシリアライズしたものを拡張メソッドのLoadXmlで読もうとした
public void SaveXml(string path)
{
Xmldata<Type> xmldata = new Xmldata<Type>();
xmldata.data = this.ToArray();
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(Xmldata<Type>));
// xmlファイルに書き込み
xml.Serialize(fs, xmldata);
}
}
#region 例外処理
catch
{
}
#endregion
return;
}
}
static class Linq
{
public class XmlData<Type> { public Type[] data; }
public static void LoadXml<Type>(this List<Type> list, string path)
{
list.Clear();
XmlData<Type> xmldata = null;
XmlDocument xdoc = new System.Xml.XmlDocument();
XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(XmlData<Type>));
xdoc.PreserveWhitespace = true;
xdoc.Load(path);
XmlNodeReader xnr = new System.Xml.XmlNodeReader(xdoc.DocumentElement);
xmldata = (XmlData<Type>)xml.Deserialize(xnr);
for (int i = 0; i < xmldata.data.Length; i++)
list.Add(xmldata.data[i]);
}
public static void SaveXml<Type>(this List<Type> list, string path)
{
XmlData<Type> xmldata = new XmlData<Type>();
xmldata.data = list.ToArray();
using (FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xml = new XmlSerializer(typeof(XmlData<Type>));
xml.Serialize(fs, xmldata);
}
}
}