DataSet和XML的详细分析
DataSet和XML文件转换
//查看XML文件
using System.Xml;
using System.IO;
using System.Data.SqlClient;
private void btnView_Click(object sender, System.EventArgs e)
{
// 清除ListBox的所有项
lbItem.Items.Clear();
XmlNodeList ndList = BuildXml().GetElementsByTagName("XMLAuthors");
foreach(XmlNode xn in ndList)
lbItem.Items.Add (xn.InnerText);
}
//生成XML
private void btnBuild_Click(object sender, System.EventArgs e)
{
BuildFile();
}
private void BuildFile()
{
// 要写入文件的路径
string filepath = Server.MapPath("Authors.xml");
CreateDateSet().WriteXml(filepath);
}
//读取XML文件
private void btnLoad_Click(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
string filepath = Server.MapPath("Authors.xml");
ds.ReadXml (filepath);
dgViewXml.DataSource = ds;
dgViewXml.DataMember = "XMLAuthors";
dgViewXml.DataBind();
}
//从数据库生成DataSet
public DataSet CreateDateSet()
{
// 创建到Sql Server数据库的连接
string strconn="Server=(local);Database=Pubs;uid=sa;pwd=12345678";
SqlConnection conn = new SqlConnection ();
conn.ConnectionString = strconn;
conn.Open();
// 创建关于Authors表的数据集
string strAuthorsSql = "SELECT * FROM authors";
SqlDataAdapter da = new SqlDataAdapter(strAuthorsSql,conn);
da.SelectCommand.CommandType = CommandType.Text;
// 声明DataSet
DataSet ds = new DataSet();
da.Fill (ds,"XMLAuthors");
// 返回DataSet数据集
return ds;
}
//创建XmlDocument对象
public XmlDocument BuildXml()
{
// 声明MemoryStream对象
XmlDocument doc=new XmlDocument();
MemoryStream mStrm = new MemoryStream ();
StreamReader sRead = new StreamReader(mStrm);
// 调用CreateDataSet方法把DataSet中的数据输出
CreateDateSet().WriteXml (mStrm,XmlWriteMode.IgnoreSchema);
// 从数据流的开始位置进行搜索
mStrm.Seek (0,SeekOrigin.Begin);
// 将数据流加载到XmlDocument
doc.Load (sRead);
return doc;
}
XML文档读写
//创建
using System.Xml;
private void btnCreate_Click(object sender, System.EventArgs e)
{
int nFQ;
XmlDocument doc = new XmlDocument();
XmlAttribute newAtt;
//定义XML文档头文件
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0",null,null);
doc.AppendChild(dec);
XmlElement docRoot = doc.CreateElement("Orders");
doc.AppendChild(docRoot);
for(int i=0;i<12;i++)
{
XmlNode Order = doc.CreateElement("Order");
newAtt = doc.CreateAttribute("Quantity");
nFQ = 10*i +i;
newAtt.Value = nFQ.ToString();
Order.Attributes.Append(newAtt);
docRoot.AppendChild(Order);
}
//保存XML文档
string strPath = Server.MapPath("OutDocument.XML");
doc.Save(strPath);
}
//读取
private void btnRead_Click(object sender, System.EventArgs e)
{
XmlDocument doc = new XmlDocument();
XmlElement TempNode;
string strPath = Server.MapPath("OutDocument.XML");
doc.Load(strPath);
Response.Write("文档已经加载!<br>");
XmlNodeList xnl=doc.SelectSingleNode("Orders").ChildNodes;
foreach(XmlNode xn in xnl)
{
TempNode = (XmlElement)xn;
Response.Write("Order Quantity:"+TempNode.GetAttribute("Quantity")+"<br>");
}
}
XPath的使用
using System.Xml;
private void Page_Load(object sender, System.EventArgs e)
{
XmlDocument XDoc;
XmlNodeList XNodes;
XDoc = new XmlDocument();
XDoc.Load(Server.MapPath("Orders.xml"));
XNodes = XDoc.DocumentElement.SelectNodes("//Customer[starts-with(@Name,'A')]/Order");
//以下没有使用缩略语法
//XNodes = XDoc.DocumentElement.SelectNodes("descendant::Customer[start-with(attribute::Name,'A')]/child::Order");
Response.Write("找到 "+XNodes.Count.ToString()+"个节点<br>");
foreach(XmlNode XNode in XNodes)
{
Response.Write("Customer "+XNode.ParentNode.Attributes.GetNamedItem("Name").Value
+" Ordered "+XNode.Attributes.GetNamedItem("Quantity").Value
+" "+XNode.InnerText+"<br>");
}
}
Select的使用
private void Page_Load(object sender, System.EventArgs e)
{
DataSet StudentDS = new DataSet();
StudentDS.ReadXmlSchema(Server.MapPath("Students.XSD" ));
StudentDS.ReadXml(Server.MapPath("Students.XML") );
// Accept changes now so that original data from the XML file
// is considered "original".
StudentDS.AcceptChanges();
Response.Write("GPA小于2的学生有:<br>");
DataRow[] SelectRows = StudentDS.Tables["Student"].Select( "GPA < 2.0" );
for (int i=0; i< SelectRows.Length; i++)
{
Response.Write( SelectRows[i]["Name"]+"<br>" );
}
SelectRows = StudentDS.Tables["Student"].Select( "Age>16" );
Response.Write("<br>大于16岁的学生有:<br>");
for (int i=0; i<SelectRows.Length; i++)
{
Response.Write( SelectRows[i]["Name"]+"<br>" );
}
// now add a new row so we can test out versioning
// selects.
DataRow NewRow = StudentDS.Tables["Student"].NewRow();
NewRow["ID"] = 8;
NewRow["Name"] = "The New Kid";
NewRow["Age"] = 17;
NewRow["GPA"] = 3.99;
NewRow["LockerCombination"] = "5-9-30";
StudentDS.Tables["Student"].Rows.Add( NewRow );
NewRow = StudentDS.Tables["Student"].NewRow();
NewRow["ID"] = 9;
NewRow["Name"] = "Girl Genius";
NewRow["Age"] = 12;
NewRow["GPA"] = 4.15;
NewRow["LockerCombination"] = "3-2-1";
StudentDS.Tables["Student"].Rows.Add( NewRow );
// important here not to AcceptChanges, so the DataSet still knows
// which rows are "new".
Response.Write("<br>新增并且年龄大于16的学生:<br>");
Console.WriteLine("-------------------------------------------");
SelectRows = StudentDS.Tables["Student"].Select("Age > 16", "", DataViewRowState.Added );
for (int i=0; i<SelectRows.Length; i++)
{
Response.Write( SelectRows[i]["Name"]+"<br>" );
}
}
DataView的使用
private void Page_Load(object sender, System.EventArgs e)
{
DataSet StudentDS = new DataSet();
//StudentDS.ReadXmlSchema( Server.MapPath("Students.XSD" ));
StudentDS.ReadXml(Server.MapPath("Students.XML") );
// again, accept the changes so the dataset has an "original" state.
StudentDS.AcceptChanges();
DataView AddedStudents = new DataView( StudentDS.Tables["Student"] );
AddedStudents.RowStateFilter = DataViewRowState.Added;
PrintStudents(AddedStudents, "新添加的学生列表:");
DataView Prodigies = new DataView( StudentDS.Tables["Student"] );
Prodigies.RowFilter = "(GPA > 3.90) AND (Age < 15)";
PrintStudents( Prodigies, "优秀学生列表:");
// now modify the original table (not the views).
DataRow NewRow = StudentDS.Tables["Student"].NewRow();
NewRow["ID"] = 8;
NewRow["Name"] = "The New Kid";
NewRow["Age"] = 17;
NewRow["GPA"] = 3.99;
NewRow["LockerCombination"] = "5-9-30";
StudentDS.Tables["Student"].Rows.Add( NewRow );
NewRow = StudentDS.Tables["Student"].NewRow();
NewRow["ID"] = 9;
NewRow["Name"] = "Girl Genius";
NewRow["Age"] = 12;
NewRow["GPA"] = 4.15;
NewRow["LockerCombination"] = "3-2-1";
StudentDS.Tables["Student"].Rows.Add( NewRow );
PrintStudents( AddedStudents, "添加后的学生列表(已经更新)");
PrintStudents( Prodigies, "优秀学生列表(已经更新)");
}
private void PrintStudents(DataView dv, string Caption)
{
Response.Write("<br>"+Caption);
for (int i=0; i<dv.Count; i++)
{
Response.Write("<br>"+dv[i]["Name"]);
}
Response.Write("<br>"+dv.Count.ToString()+"个学生");
}
Xml文档失真
private void Page_Load(object sender, System.EventArgs e)
{
DataSet myDS = new DataSet();
myDS.ReadXmlSchema(Server.MapPath("Books.xsd"));
myDS.ReadXml(Server.MapPath("Books.xml"));
myDS.WriteXml(Server.MapPath("Books_After.XML"));
}
XmlDataDocument的使用
private void Page_Load(object sender, System.EventArgs e)
{
DataSet DSStudentClasses = new DataSet();
XmlNode tmpNode;
DSStudentClasses.ReadXmlSchema( Server.MapPath("StudentClasses.XSD" ));
XmlDataDocument XDocStudents = new XmlDataDocument( DSStudentClasses );
XDocStudents.Load(Server.MapPath( "Students.XML") );
Response.Write("Students in DataSet:");
foreach (DataRow _Row in DSStudentClasses.Tables["Student"].Rows )
{
Response.Write(_Row["Name"]+":"+_Row["GPA"]);
tmpNode = XDocStudents.GetElementFromRow( _Row );
//XmlElement TempNode = (XmlElement)tmpNode;
Response.Write("<br>Locker Combination (from XML, not DataSet): "+tmpNode.SelectSingleNode("LockerCombination"));
//LockerCombination不在DataSet中,所以当下面取消注释时,会报错。
//Response.Write("<br>Locker Combination (from DS):"+ _Row["LockerCombination"] );
foreach (DataRow _Class in _Row.GetChildRows("StudentClasses") )
{
Response.Write("<br>"+_Class["Title"] );
}
}
}
XSL转换
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
private void Page_Load(object sender, System.EventArgs e)
{
XslTransform xslt = new XslTransform();
xslt.Load(Server.MapPath( "StudentsToHTML.xsl") );
XPathDocument XDoc = new XPathDocument(Server.MapPath( "Students.XML" ));
XmlWriter writer = new XmlTextWriter( Server.MapPath("Students.HTML"), System.Text.Encoding.UTF8 );
xslt.Transform( XDoc, null, writer );
}
本文地址:http://www.45fan.com/a/question/69591.html