读写XML 节点的例子,如何用C#写
using System.Xml;
//处理XML必须加的Namespace,还需在References中加System.XML.Dll
using System.IO;
//读XML文件必须加的Namespace
然后在Page_Load中加入如下代码:
protected void Page_Load(object sender, EventArgs e){
string datafile="guest.xml" ;
//假设XML文件名为guest.xml
StreamReader tyj=new StreamReader(Server.MapPath(datafile));
XmlDataDocument datadoc = new XmlDataDocument();
//创建该对象为了读取XML
datadoc.DataSet.ReadXml(tyj);
//读取guest.xml文件内容
DataGrid1.DataSource = datadoc.DataSet.Tables[0].DefaultView;
//设置DataGrid数据源
DataGrid1.DataBind();
//绑定
datadoc=null ;
//释放资源
tyj.Close();}
//释放StreamReader类,这非常重要,否则下次打开会显示文件已经被使用
对应于显示用的Web Form中DataGrid的功能,我们需要增加下面的函数:
protected void OnSelectName(object sender,EventArgs e) {
Session["select_name"]=(string)DataGrid1.SelectedItem.Cells[1].Text.ToString();
//把选定的 DataGrid某行中的一个单元中的值(Name)存入一个会话变量中,以便下一页用
Response.Redirect("xml_manage.aspx");}
//转到有增加删除功能的管理页
Web Form加入以下代码:
<asp:DataGrid id=DataGrid1 runat="server" onselectedindexchanged="OnSelectName" >
<property name="Columns">
<asp:buttoncolumn Text="选择" commandname="Select" />
</property>
代码的作用是当按了“选择”按钮后,执行OnSelectName()中的程序,把选定的 DataGrid中某行中的一个单元中的值(Name)存入一个会话变量中,然后转到下一页。
增加XML文件内容
在Web Form中增加相应的几个TextBox和一个用于提交的Button,如本文附图所示,并为这button增加如下代码:
string datafile = "guest.xml" ;XmlDocument xmldocument = new XmlDocument() ;
xmldocument.Load(Server.MapPath(datafile)) ;
//把guest.xml读到xmldocument中
DocumentNavigator navigator = new DocumentNavigator(xmldocument) ;
//最重要的类
navigator.MoveToDocumentElement() ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Element, "Guest","","") ;//插入节点Guest
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Element, "Name","","") ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Text,"Name","","") ;
navigator.Value=Name.Text ;
//为该节点赋值
navigator.MoveToParent() ;
//返回父节点 Guest
……
//使用同类语句,在元素Name下插入另一些元素如Country、E-mail地址和留言等
xmldocument.Save(Server.MapPath(datafile));
//最后保存这个XML文档
navigator=null ;
xmldocument=null ;
//释放XML文档,这样其他程序可以用它
上述代码使用DocumentNavigator类增加元素和内容,注意使用后要释放资源。
删除XML文件内容
删除选定记录,对于你上面选择的节点,下面代码可查找到该节点并清除选中的信息:
string datafile = "guest.xml" ;
XmlDocument xmldocument = new XmlDocument() ;
xmldocument.Load(Server.MapPath(datafile)) ;
//把guest.xml读到xmldocument中
DocumentNavigator navigator = new DocumentNavigator(xmldocument) ;
navigator.MoveToDocumentElement() ;
navigator.Select("/Guests/Guest[Name='"+Session["select_name"]+"']");
//参数是Xpath
navigator.RemoveSelected();
//执行删除
xmldocument.Save(Server.MapPath(datafile));
//最后保存这个XML文档
navigator=null;
//释放类
xmldocument=null ;
//释放XML文档,这样其他程序可以用它
如需将XML文件中所有信息清除,使用“navigator.RemoveChildren();”语句即可实现
////////////////////////// 读写操作 |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private void DemonstrateReadWriteXMLDocumentWithXMLReader(){
// Create a DataSet with one table and two columns.
DataSet OriginalDataSet = new DataSet("myDataSet");
OriginalDataSet.Namespace= "NetFrameWork";
DataTable myTable = new DataTable("myTable");
DataColumn c1 = new DataColumn("id", Type.GetType("System.Int32"));
c1.AutoIncrement= true;
DataColumn c2 = new DataColumn("item");
myTable.Columns.Add(c1);
myTable.Columns.Add(c2);
OriginalDataSet.Tables.Add(myTable);
// Add ten rows.
DataRow newRow;
for(int i = 0; i < 10; i++){
newRow = myTable.NewRow();
newRow["item"]= "item " + i;
myTable.Rows.Add(newRow);
}
OriginalDataSet.AcceptChanges();
// Print out values of each table in the DataSet using the
// function defined below.
PrintValues(OriginalDataSet, "Original DataSet");
// Write the XML schema and data to file with FileStream.
string xmlFilename = "myXmlDocument.xml";
// Create FileStream
System.IO.FileStream fsWriteXml = new System.IO.FileStream
(xmlFilename, System.IO.FileMode.Create);
// Create an XmlTextWriter to write the file.
System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter
(fsWriteXml, System.Text.Encoding.Unicode);
// Use WriteXml to write the document.
OriginalDataSet.WriteXml(xmlWriter);
// Close the FileStream.
fsWriteXml.Close();
// Dispose of the original DataSet.
OriginalDataSet.Dispose();
// Create a new DataSet.
DataSet newDataSet = new DataSet("New DataSet");
// Read the XML document back in.
// Create new FileStream to read schema with.
System.IO.FileStream fsReadXml = new System.IO.FileStream
(xmlFilename, System.IO.FileMode.Open);
// Create an XmlTextReader to read the file.
System.Xml.XmlTextReader myXmlReader =
new System.Xml.XmlTextReader(fsReadXml);
// Read the XML document into the DataSet.
newDataSet.ReadXml(myXmlReader);
// Close the XmlTextReader
myXmlReader.Close();
// Print out values of each table in the DataSet using the
// function defined below.
PrintValues(newDataSet,"New DataSet");
}
private void PrintValues(DataSet ds, string label){
Console.WriteLine("" + label);
foreach(DataTable t in ds.Tables){
Console.WriteLine("TableName: " + t.TableName);
foreach(DataRow r in t.Rows){
foreach(DataColumn c in t.Columns){
Console.Write("\t " + r[c] );
}
Console.WriteLine();
}
}
}
//处理XML必须加的Namespace,还需在References中加System.XML.Dll
using System.IO;
//读XML文件必须加的Namespace
然后在Page_Load中加入如下代码:
protected void Page_Load(object sender, EventArgs e){
string datafile="guest.xml" ;
//假设XML文件名为guest.xml
StreamReader tyj=new StreamReader(Server.MapPath(datafile));
XmlDataDocument datadoc = new XmlDataDocument();
//创建该对象为了读取XML
datadoc.DataSet.ReadXml(tyj);
//读取guest.xml文件内容
DataGrid1.DataSource = datadoc.DataSet.Tables[0].DefaultView;
//设置DataGrid数据源
DataGrid1.DataBind();
//绑定
datadoc=null ;
//释放资源
tyj.Close();}
//释放StreamReader类,这非常重要,否则下次打开会显示文件已经被使用
对应于显示用的Web Form中DataGrid的功能,我们需要增加下面的函数:
protected void OnSelectName(object sender,EventArgs e) {
Session["select_name"]=(string)DataGrid1.SelectedItem.Cells[1].Text.ToString();
//把选定的 DataGrid某行中的一个单元中的值(Name)存入一个会话变量中,以便下一页用
Response.Redirect("xml_manage.aspx");}
//转到有增加删除功能的管理页
Web Form加入以下代码:
<asp:DataGrid id=DataGrid1 runat="server" onselectedindexchanged="OnSelectName" >
<property name="Columns">
<asp:buttoncolumn Text="选择" commandname="Select" />
</property>
代码的作用是当按了“选择”按钮后,执行OnSelectName()中的程序,把选定的 DataGrid中某行中的一个单元中的值(Name)存入一个会话变量中,然后转到下一页。
增加XML文件内容
在Web Form中增加相应的几个TextBox和一个用于提交的Button,如本文附图所示,并为这button增加如下代码:
string datafile = "guest.xml" ;XmlDocument xmldocument = new XmlDocument() ;
xmldocument.Load(Server.MapPath(datafile)) ;
//把guest.xml读到xmldocument中
DocumentNavigator navigator = new DocumentNavigator(xmldocument) ;
//最重要的类
navigator.MoveToDocumentElement() ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Element, "Guest","","") ;//插入节点Guest
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Element, "Name","","") ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Text,"Name","","") ;
navigator.Value=Name.Text ;
//为该节点赋值
navigator.MoveToParent() ;
//返回父节点 Guest
……
//使用同类语句,在元素Name下插入另一些元素如Country、E-mail地址和留言等
xmldocument.Save(Server.MapPath(datafile));
//最后保存这个XML文档
navigator=null ;
xmldocument=null ;
//释放XML文档,这样其他程序可以用它
上述代码使用DocumentNavigator类增加元素和内容,注意使用后要释放资源。
删除XML文件内容
删除选定记录,对于你上面选择的节点,下面代码可查找到该节点并清除选中的信息:
string datafile = "guest.xml" ;
XmlDocument xmldocument = new XmlDocument() ;
xmldocument.Load(Server.MapPath(datafile)) ;
//把guest.xml读到xmldocument中
DocumentNavigator navigator = new DocumentNavigator(xmldocument) ;
navigator.MoveToDocumentElement() ;
navigator.Select("/Guests/Guest[Name='"+Session["select_name"]+"']");
//参数是Xpath
navigator.RemoveSelected();
//执行删除
xmldocument.Save(Server.MapPath(datafile));
//最后保存这个XML文档
navigator=null;
//释放类
xmldocument=null ;
//释放XML文档,这样其他程序可以用它
如需将XML文件中所有信息清除,使用“navigator.RemoveChildren();”语句即可实现
////////////////////////// 读写操作 |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private void DemonstrateReadWriteXMLDocumentWithXMLReader(){
// Create a DataSet with one table and two columns.
DataSet OriginalDataSet = new DataSet("myDataSet");
OriginalDataSet.Namespace= "NetFrameWork";
DataTable myTable = new DataTable("myTable");
DataColumn c1 = new DataColumn("id", Type.GetType("System.Int32"));
c1.AutoIncrement= true;
DataColumn c2 = new DataColumn("item");
myTable.Columns.Add(c1);
myTable.Columns.Add(c2);
OriginalDataSet.Tables.Add(myTable);
// Add ten rows.
DataRow newRow;
for(int i = 0; i < 10; i++){
newRow = myTable.NewRow();
newRow["item"]= "item " + i;
myTable.Rows.Add(newRow);
}
OriginalDataSet.AcceptChanges();
// Print out values of each table in the DataSet using the
// function defined below.
PrintValues(OriginalDataSet, "Original DataSet");
// Write the XML schema and data to file with FileStream.
string xmlFilename = "myXmlDocument.xml";
// Create FileStream
System.IO.FileStream fsWriteXml = new System.IO.FileStream
(xmlFilename, System.IO.FileMode.Create);
// Create an XmlTextWriter to write the file.
System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter
(fsWriteXml, System.Text.Encoding.Unicode);
// Use WriteXml to write the document.
OriginalDataSet.WriteXml(xmlWriter);
// Close the FileStream.
fsWriteXml.Close();
// Dispose of the original DataSet.
OriginalDataSet.Dispose();
// Create a new DataSet.
DataSet newDataSet = new DataSet("New DataSet");
// Read the XML document back in.
// Create new FileStream to read schema with.
System.IO.FileStream fsReadXml = new System.IO.FileStream
(xmlFilename, System.IO.FileMode.Open);
// Create an XmlTextReader to read the file.
System.Xml.XmlTextReader myXmlReader =
new System.Xml.XmlTextReader(fsReadXml);
// Read the XML document into the DataSet.
newDataSet.ReadXml(myXmlReader);
// Close the XmlTextReader
myXmlReader.Close();
// Print out values of each table in the DataSet using the
// function defined below.
PrintValues(newDataSet,"New DataSet");
}
private void PrintValues(DataSet ds, string label){
Console.WriteLine("" + label);
foreach(DataTable t in ds.Tables){
Console.WriteLine("TableName: " + t.TableName);
foreach(DataRow r in t.Rows){
foreach(DataColumn c in t.Columns){
Console.Write("\t " + r[c] );
}
Console.WriteLine();
}
}
}