The first two articles read the configuration file, and then read the XML file:
Suppose there is an XML file: paramconfig. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Books kinds = "7">
<Book name = "math" Price = "20"> </book>
<Book name = "Chinese" Price = "10"> </book>
<Book name = "English" Price = "15"> </book>
<Book name = "chemistry" Price = "25"> </book>
<Book name = "biology" Price = "20"> </book>
<Book name = "physics" Price = "30"> </book>
<Book name = "History" Price = "15"> </book>
</Books>
</Configuration>
// File path
String filepath = system. appdomain. currentdomain. basedirectory + @ "\ paramconfig. xml ";
/// <Summary>
/// Load XML
/// </Summary>
Private void loadxml ()
{
String filepath = system. appdomain. currentdomain. basedirectory + @ "\ paramconfig. xml ";
Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load (filepath );
Xmlnode parent, root;
Parent = xmldoc. selectsinglenode ("configuration ");
If (null = parent)
{
Return;
}
Root = parent. selectsinglenode ("books ");
If (null = root)
{
Return;
}
Xmlnodelist nodelist = root. childnodes;
If (null = nodelist | nodelist. Count <= 0)
{
Return;
}
Foreach (xmlnode node in nodelist)
{
Xmlelement element = node as xmlelement;
This. richtextbox1.appendtext (string. Format ("name = {0}, price = {1}", element. getattribute ("name "),
Element. getattribute ("price") + "\ r \ n ");
}
}
/// <Summary>
/// Save the XML
/// </Summary>
Private void savexml ()
{
List <book> booklist = new list <book> ();
Booklist. Add (New Book ("math", "25 "));
Booklist. Add (New Book ("Chinese", "5 "));
Booklist. Add (New Book ("biology", "10 "));
Xmldocument xmldoc = new xmldocument ();
If (! System. Io. file. exists (filepath ))
{
Xmldeclaration dec = xmldoc. createxmldeclaration ("1.0", "UTF-8", String. Empty );
Xmldoc. appendchild (DEC );
}
Else
{
Xmldoc. Load (filepath );
}
Xmlnode parent, root;
Parent = xmldoc. selectsinglenode ("configuration ");
If (null = parent)
{
Parent = xmldoc. createelement ("configuration ");
Xmldoc. appendchild (parent );
}
Root = parent. selectsinglenode ("books ");
If (null = root)
{
Root = xmldoc. createelement ("books ");
Parent. appendchild (Root );
}
Root. removeall ();
(Xmlelement) root). setattribute ("kinds", Booklist. Count. tostring ());
Foreach (Book pbook in booklist)
{
Xmlelement bookelement = xmldoc. createelement ("book ");
Bookelement. setattribute ("name", pbook. Name );
Bookelement. setattribute ("price", pbook. Price );
Root. appendchild (bookelement );
}
Xmldoc. Save (filepath );
}
Private void btnsave_click (Object sender, eventargs E)
{
Savexml ();
}
Private void btnload_click (Object sender, eventargs E)
{
Loadxml ();
}