• 在ADO.NET组件中DataSet是其核心组

件之一,它提供了独立于数据源的数据

访问,为了实现这种平台互用性和可伸

缩的数据访问,ADO.NET采用了基于

XML数据的传输格式,XML在这里充当

了至关重要的脚色。

• 当数据传输时,ADO.NET是将DataSet

表述为XML,然后以XML格式传递给其

他组件。

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Data.SqlClient;
namespace AddsAndXML
{
/**//**//**//// <summary>
/// dsAndXml 的摘要说明。
/// </summary>
public class dsAndXml : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnView;
protected System.Web.UI.WebControls.ListBox lbItem;
protected System.Web.UI.WebControls.Button btnLoad;
protected System.Web.UI.WebControls.DataGrid dgViewXml;
protected System.Web.UI.WebControls.Button btnBuild;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}

//从数据库生成DataSet
public DataSet CreateDateSet()
{
// 创建到Sql Server数据库的连接
string strconn="Server=(local);Database=Pubs;uid=sa;pwd=111";
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文件的方法BuildFile():
private void BuildFile()
{
// 要写入文件的路径
string filepath = Server.MapPath("Authors.xml");
CreateDateSet().WriteXml(filepath);

}


Web Form Designer generated codeWeb Form Designer generated code#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/**//**//**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnView.Click += new System.EventHandler(this.btnView_Click);
this.btnBuild.Click += new System.EventHandler(this.btnBuild_Click);
this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

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);

}

private void btnBuild_Click(object sender, System.EventArgs e)
{
BuildFile();
}

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();

}
}
}

XmlDocument类
• 位于System.Xml名称空间
• 是XML文档的内存表示
• 当一个XML文档被载入时,它作为
XmlNode对象群组的一部分被载入到一树
型描述中。每个XmlNode对象可以有多个
子XmlNode对象,但是只能有一个父节点
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

• XPath(XML 路径语言)是用来查询和定位XML
文档里的元素以及文本的一种通用查询方法。
• 许多人将XPath看作Internet的SQL语言。
• XPath语法使用称为表达式的模式。初始化时结
果集中没有任何东西,利用XPath表达式使得出
现在结果集里的节点形成特定的层次结构并符合
一定的条件。
• XPath上下文:是我们将要查询文档的文档树中
一个特定的节点。可以认为是查询的一个起始点。
XPath表达式
• 由位置步组成。它由一个轴、一个节点测
试和可选择的一系列谓词构成。通过使用
反斜杠连接多个位置步形成位置路径,产
生一组节点作为结果。
• /Books/book/title:要求元素Books的子元
素book的所有子元素title。
• /Books/book[@Price<21.99]/title:返回
Books根元素下book子元素中,所有Price
属性值小于21.99的book的所有title子元素
XPath表达式
• 位置步:表达式中由反斜杠分开的每个部
分被称为一个位置步。
• 轴:是与上下文节点相对的文档的一部
分,它定义了一组与当前节点有特定层次
关系的节点。
• 节点测试:可以用来指示位置路径中一组
合法节点的任何表达式。节点测试通过名
字或类型筛选初始结果集。
– child::text():返回所有文本子节点。
• 谓词:true或false的一个表达式。

• 轴心包括:self、child、parent、
descendent、ancestor、attribute、
namespace、following、preceding
• child::Customer:返回当前节点子元素中的
所有Customer元素
• descendent::OrderItem:返回节点名
为”OrderItem“的所有后代
XPath表达式示例
• ./Order将找到当前上下文中名为Order的所有元素
• /Order将找到文档树中根下所有名为Order的元素
• //Order将在文档树的任何地方找到所有名为Order
的元素,不管深度或层次结构
• child::book[attribute::publisher=‘张三’]
• child::book[@publisher=‘张三’]
• descendent::book[count(child::chapter)>5]:用
count函数检索所有chapter大于5的后代book节点
• child::book[start-with(attribute::publisher,’张’)]:使
用start-with函数检索所有publisher属性以’张’开头
的book子节点.
XPath缩略语法
• //代表后代轴
• @代表属性轴
• .代表自己
• ..代表父节点
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>");
}
}DataSet过滤

• Select方法:通过一个过滤字符串来过滤表
中的行
• DataView
Select方法
• 它返回一组符合查询中所指定标准的
DataRow对象。
• 除了给出过滤表达式以外,还可以提供一
个DataRowViewState,以便选择所有不仅
符合给定标准而且还有指定版本(比如添
加、源数据、删除)的行
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

• 是一个给定DataTable的可绑定的定制视图。
• 通过定制视图,我们可以控制视图允许用
户看什么DataViewRowState
• 也可以提供筛选表达式,以控制哪些行对
于视图来说是可以访问的
• 除了允许用户查看特定数据外,也可以通
过视图修改原始表中的数据,只要修改符
合视图的约束。
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()+"个学生");
}


使用XmlDataDocument
• 失真:
– 当DataSet已有一个模式但不是从文档推出来
的模式时,它将只载入模式定义的数据。如果
修改DataSet然后保存到XML,则保存后的
XML不会含有模式以外的属性。
– 另外,字符、格式化字符和空格-它们可能是
原始文档中所需要的或是有意义的-都不会在
DataSet生成的文档中出现
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
• XmlDataDocument允许通过DataSet
来存取、检索和操作结构化的XML数
据。
• XmlDataDocument将保护正与
DataSet结合的XML文档的保真度
• XmlDataDocument与DataSet同步工
作,当一个对象有所改变时,该改变
能被及时地通知给其他对象。
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和XSLT转换XML
• XSL:扩展样式表语言,可以通过它来把
XML转换为其他的文本格式
• XSL转换包括发现或者选择一个模式匹配,
通过使用XPath选择一个结果集,然后对结
果集中的每一项,为这些匹配定义结果输
出。
• XSL是一个功能强大的工具,可以把XML转
换成任何你想要的格式。
​​/Files/cmzzlh/08UseXSLT.rar​​


from: ​​javascript:void(0)​​
other:
​​​http://hi.baidu.com/fumychina/blog/item/adc3bede45859e58ccbf1ab6.html​​​
​​​http://www.window07.com/dev/web/net/2006-3-3/k73431.htm​​​




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 );

}