将对象序列化成xml以及反序列化
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace DLXML
{
[XmlRoot("Test",IsNullable=false)]
public class Test
{
string property1 = "A";
public Test()
{
}
public string Property1
{
get { return property1; }
set { property1 = value; }
}
string property2 = "B";
public string Property2
{
get { return property2; }
set { property2 = value; }
}
string property3 = "C";
public string Property3
{
get { return property3; }
set { property3 = value; }
}
IList files = null;
[XmlArrayAttribute("Files")]
public IList Files
{
get {
if (files == null)
{
files = new ArrayList();
}
return files; }
set {
if (files == null)
{
files = new ArrayList();
}
files = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;
namespace DLXML
{
public class XML
{
/// <summary>
/// This property gets or sets the data directory in which you use.
/// data store.
/// </summary>
private string _dataDirectory;
public string DataDirectory
{
get { return _dataDirectory; }
set { _dataDirectory = value; }
}
public void CreateXML( Test test)
{
XmlSerializer xs = new XmlSerializer(typeof(Test));
TextWriter tw = new StreamWriter(DataDirectory);
Test tt = new Test();
if (test != null)
{
tt = test;
xs.Serialize(tw, tt);
tw.Close();
}
}
public Test ReadXML()
{
Test tt = new Test();
try
{
XmlSerializer xs = new XmlSerializer(typeof(Test));
xs.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
xs.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
FileStream fs = new FileStream(DataDirectory, FileMode.Open);
tt = (Test)xs.Deserialize(fs);
}
catch (Exception ee)
{
MessageBox.Show(ee.Message, "ReadXMLErrot");
}
return tt;
}
protected void serializer_UnknownNode(object sender, XmlNodeEventArgs e)
{
MessageBox.Show(e.Name + "/n" + e.Text,"NodeError");
}
protected void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
MessageBox.Show(attr.Name + "/n" + attr.Value,"AttributeErrot");
}
}
}