XML và ADO.NET
XML là lớp kết nối giữa ADO.NET với phần còn lại của thế giới. ADO.NET được thiết
kế từ sự có phát triển của việc sử dụng môi trường XML. XML được sử dụng để truyền
dữ liệu trừ nơi lưu trữ vào ứng dụng hoặc trang web. Từ khi ADO.NET sử dụng XML
như là môi trường truyền tải, dữ liệu có thể trao đổi giữa ứ
ng dụng và hệ thống nó không
chỉ xảy ra trong ADO.NET. Bởi sự quan trọng của XML trong ADO.NET, có một vài
đặc tính mạnh mẽ trong ADO.NET cho phép đọc và ghi các tài liệu XML. Không gian
tên System.Xml cũng chứa các lớp có thể hủy và sử dụng dữ liệu quan hệ ADO.NET.
Chuyển dữ liệu ADO.NET thành XML
Trong ví dụ đầu tiên chúng ta sẽ xem xét cách dùng ADO.NET, streams, và XML để
"pull" một vài dữ liệu từ cơ sở dữ liệu Northwind vào một DataSet, load một đối tượng
XmlDocument với XML từ DataSet, và load XML vào môt listbox.
Để chạy ứng dụng
chúng ta cần chèn các câu lệnh using sau:
using System.Data;
using System.Xml;
using System.Data.SqlClient;
using System.IO;
Nếu sử dụng XmlDocument, chúng ta cũng cần phải thêm dòng sau:
private XmlDocument doc = new XmlDocument();
Các ví dụ ADO.NET thường có thêm một DataGrid trong forms. Nó cho phép chúng ta
thấy dữ liệu trong ADO.NET DataSet. Đây là mã cho ví dụ đầu tiên, mã có thể được tìm
thấy trong thư mục ADOSample1
:
private void button1_Click(object sender, System.EventArgs e)
{
//create a dataset
DataSet ds = new DataSet("XMLProducts");
DiffGram
IgnoreSchema được dùng nếu bạn không muốn WriteXml() ghi một inline schema vào
đầu file XML; dùng tham số WriteSchema nếu bạn muốn như vậy. Chúng ta sẽ xem xét
DiffGrams ở phần sau.
ds.WriteXml(strmWrite,XmlWriteMode.IgnoreSchema);
memStrm.Seek(0,SeekOrigin.Begin);
//read from the memory stream to an XmlDocument object
doc.Load(strmRead);
//get all of the products elements
XmlNodeList nodeLst=doc.GetElementsByTagName("ProductName");
//load them into the list box
foreach(XmlNode nd in nodeLst)
listBox1.Items.Add(nd.InnerText);
}
private void listBox1_SelectedIndexChanged(object sender,
System.EventArgs e)
{
//when you click on the listbox,
//a message box appears with the unit price
string srch="XMLProducts/products[ProductName=" +
'"'+ listBox1.SelectedItem.ToString() + '"' + "]";
XmlNode foundNode=doc.SelectSingleNode(srch);
if(foundNode!=null)
MessageBox.Show(foundNode.SelectSingleNode("UnitPrice").InnerText);
else
MessageBox.Show("Not found");
}
Đây là màn hình, bạn có thể nhìn thấy kết quả trong danh sách cũng như trong DataGrid:
Nếu bạn chỉ muốn schema, bạn có thể gọi WriteXmlSchema() thay vì WriteXml().
Chúng ta cân nó bởi vì giờ đây chúng ta sẽ dùng XmlDataDocument. Đây là mã, có thể
tìm thấy trong thư mục ADOSample2
:
private void button1_Click(object sender, System.EventArgs e)
{
//create a dataset
DataSet ds=new DataSet("XMLProducts");
//connect to the northwind database and
//select all of the rows from products table
//make changes to connect string to match your login and server name
SqlConnection conn=new SqlConnection
(@"server=GLYNNJ_CS\NetSDK;uid=sa;pwd=;database=northwind");
SqlDataAdapter da=new SqlDataAdapter("SELECT * FROM products",conn);
//fill the dataset
da.Fill(ds,"products");
//load data into grid
dataGrid1.DataSource=ds;
dataGrid1.DataMember="products";
doc=new XmlDataDocument(ds);
//get all of the products elements
XmlNodeList nodeLst=doc.GetElementsByTagName("ProductName");
//load them into the list box
//we'll use a for loop this time
for(int ctr=0;ctr<nodeLst.Count;ctr++)
listBox1.Items.Add(nodeLst[ctr].InnerText);
}
<xs:element name="ProductName" type="xs:string"
minOccurs="0" />
<xs:element name="SupplierID" type="xs:int"
minOccurs="0" />
<xs:element name="CategoryID" type="xs:int"
minOccurs="0" />
<xs:element name="QuantityPerUnit" type="xs:string"
minOccurs="0" />
<xs:element name="UnitPrice" type="xs:decimal"
minOccurs="0" />
<xs:element name="UnitsInStock" type="xs:short"
minOccurs="0" />
<xs:element name="UnitsOnOrder" type="xs:short"
minOccurs="0" />
<xs:element name="ReorderLevel" type="xs:short"
minOccurs="0" />
<xs:element name="Discontinued" type="xs:boolean"
minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<products>
<ProductID>1</ProductID>
<ProductName>Chai</ProductName>
<SupplierID>1</SupplierID>
<CategoryID>1</CategoryID>