In. net, the XmlSerializer class can be used to serialize object classes and operate xml files conveniently.
Different Nodes in the xml file correspond to different object classes, and the same ordered nodes correspond to collection classes of object classes. The demo is as follows:
Books. xml file:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Books>
<Book bookname = "c ++ language programming" author = "AAAA" Date = "2009"> </book>
<Book bookname = "Java programming" author = "BBBB" Date = "2009"> </book>
<Book bookname = "C # language programming" author = "CCCC" Date = "2009"> </book>
</Books>
Corresponding entity classes and operations
Books. cs:
Books. cs
[XmlRoot ("books")]
Public class Books: List <Book>
{
Public static Books LoadConfig (string file)
{
XmlSerializer xs = new XmlSerializer (typeof (Books ));
StreamReader sr = new StreamReader (file );
Books config = xs. Deserialize (sr) as Books;
Sr. Close ();
Return config;
}
Public void SaveConfig (string file)
{
XmlSerializer xs = new XmlSerializer (typeof (Books ));
StreamWriter sw = new StreamWriter (file );
Xs. Serialize (sw, this );
Sw. Close ();
}
}
[XmlType ("book")] // used for books. Items
Public class Book
{
Private string _ bookname;
[XmlAttribute ("bookname")]
Public string BookName
{
Get {return this. _ bookname ;}
Set {this. _ bookname = value ;}
}
Private string _ author;
[XmlAttribute ("author")]
Public string Author
{
Get {return this. _ author ;}
Set {this. _ author = value ;}
}
Private string _ date;
[XmlAttribute ("Date")]
Public string Date
{
Get {return this. _ date ;}
Set {this. _ date = value ;}
}
}
Main program call:
Form1
Public partial class Form1: Form
{
Private Books books = null;
String xmlpath = "";
Public Form1 ()
{
InitializeComponent ();
Xmlpath = Application. StartupPath + @ "\ books. xml ";
Books = Books. LoadConfig (xmlpath );
}
Private void btnDisplay_Click (object sender, EventArgs e)
{
This. bindingXmlSource. DataSource = books;
This. dgvShowData. DataSource = bindingXmlSource;
}
Private void btnSave_Click (object sender, EventArgs e)
{
Books = this. bindingXmlSource. DataSource as Books;
Books. SaveConfig (xmlpath );
}
}
Demo download