实验12: XML文件的操作
一、实验名称和性质
所属课程 | C#数据库系统设计 |
实验名称 | XML文件的操作 |
实验学时 | 2 |
实验性质 | ✓□验证 □综合 ✓□设计 |
必做/选做 | □必做 ✓□选做 |
二、实验目的
1. 了解XML文件的构成。
2. 掌握SQL SERVER中操作XML的方法。
3. 掌握C#中操作XML的基本方法
三、实验的软硬件环境要求
硬件环境要求:
PC机(单机)
使用的软件名称、版本号以及模块:
Windows XP下的SQL Server 2005(或 SQL Server 2008)
四、知识准备
1. XML节点列表
五、实验内容
(一)验证性实验
1. SQL SERVER中操作XML。
DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc ='<ROOT>
<Customer CustomerID="VINET" ContactName="Paul Henriot">
<Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">
<OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>
<OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>
</Order>
</Customer>
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">
<Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">
<OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>
</Order>
</Customer>
</ROOT>'
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
-- Execute a SELECT statement that uses the OPENXML rowset provider.
SELECT *FROM OPENXML (@idoc, '/ROOT/Customer',1)
WITH (CustomerID varchar(10), ContactName varchar(20))
SELECT *FROM
OPENXML (@idoc, '/ROOT/Customer/Order/OrderDetail',2)
WITH (OrderID int '../@OrderID',
CustomerID varchar(10)'../@CustomerID',
OrderDate datetime '../@OrderDate',
ProdID int '@ProductID',
Qty int '@Quantity')
2.C#中操作xml
(1) BookModule.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XmlDEMO
{
class BookModule
{
private string bookType;
public string BookType
{
get { return bookType; }
set { bookType = value; }
}
/// <summary>
/// 书所对应的ISBN号
/// </summary>
private string bookISBN;
public string BookISBN
{
get { return bookISBN; }
set { bookISBN = value; }
}
/// <summary>
/// 书名
/// </summary>
private string bookName;
public string BookName
{
get { return bookName; }
set { bookName = value; }
}
/// <summary>
/// 作者
/// </summary>
private string bookAuthor;
public string BookAuthor
{
get { return bookAuthor; }
set { bookAuthor = value; }
}
/// <summary>
/// 价格
/// </summary>
private double bookPrice;
public double BookPrice
{
get { return bookPrice; }
set { bookPrice = value; }
}
}
}
(2) btnXmlDocRead_Click()代码
private void btnXmlDocRead_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文档里面的注释
XmlReader reader = XmlReader.Create(@"Books.xml", settings);
xmldoc.Load(reader);
reader.Close();
XmlNode xn = xmldoc.SelectSingleNode("bookstore");//得到根节点bookstore
XmlNodeList xnl = xn.ChildNodes; // 得到根节点的所有子节点
List<BookModule > bookModuleList=new List<BookModule >();
foreach (XmlNode xn1 in xnl)
{
BookModule bookModule = new BookModule();
XmlElement xe = (XmlElement)xn1;// 将节点转换为元素,便于得到节点的属性值
bookModule.BookISBN = xe.GetAttribute("ISBN").ToString();
bookModule.BookType = xe.GetAttribute("Type").ToString();
XmlNodeList xnl0 = xe.ChildNodes; // 得到Book节点的所有子节点
bookModule.BookName = xnl0.Item(0).InnerText;
bookModule.BookAuthor = xnl0.Item(1).InnerText;
bookModule.BookPrice = Convert.ToDouble(xnl0.Item(2).InnerText);
bookModuleList.Add(bookModule);
}
dataGridView1.DataSource = bookModuleList;
}
(3)btnXmlDocWrite_Click()事件代码
private void btnXmlDocWrite_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文档里面的注释
XmlReader reader = XmlReader.Create(@"Books.xml", settings);
doc.Load(reader);
reader.Close();
XmlNode root = doc.SelectSingleNode("bookstore");
XmlElement xelKey = doc.CreateElement("book");
XmlAttribute xelType = doc.CreateAttribute("Type");
xelType.InnerText = txtTitle.Text;
xelKey.SetAttributeNode(xelType);
XmlAttribute xelType1 = doc.CreateAttribute("ISBN");
xelType1.InnerText = txtISBN .Text ;
xelKey.SetAttributeNode(xelType1);
XmlElement xelTitle = doc.CreateElement("title");
xelTitle.InnerText = txtTitle.Text;
xelKey.AppendChild(xelTitle);
XmlElement xelAuthor = doc.CreateElement("author");
xelAuthor.InnerText = txtAuthor .Text ;
xelKey.AppendChild(xelAuthor);
XmlElement xelPrice = doc.CreateElement("price");
xelPrice.InnerText =txtPrice .Text ;
xelKey.AppendChild(xelPrice);
root.AppendChild(xelKey);
doc.Save(@"Books.xml");
MessageBox.Show("数据已插入");
}
(4)btnXmlDocDelete_Click()事件代码
private void btnXmlDocDelete_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文档里面的注释
XmlReader reader = XmlReader.Create(@"Books.xml", settings);
doc.Load(reader);
reader.Close();
XmlElement xe =doc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.
string strPath = string.Format("/bookstore/book[@Type=\"{0}\"]",dataGridView1 .CurrentRow.Cells[0].Value);
MessageBox.Show(strPath);
// XmlElement selectXe = (XmlElement)xe.SelectSingleNode("/bookstore/book[author='沈刚']");//对于元素的查找例子
XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath );
selectXe.ParentNode.RemoveChild(selectXe);
doc.Save(@"Books.xml");
MessageBox.Show("数据已删除");
}
(5)btnXmlDoxUpdate_Click()事件代码
private void btnXmlDoxUpdate_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;//忽略文档里面的注释
XmlReader reader = XmlReader.Create(@"Books.xml", settings);
doc.Load(reader);
reader.Close();
XmlElement xe = doc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.
string strPath = string.Format("/bookstore/book[@Type=\"{0}\"]", dataGridView1.CurrentRow.Cells[0].Value);
XmlElement selectXe = (XmlElement)xe.SelectSingleNode(strPath);
selectXe.SetAttribute("Type", dataGridView1 .CurrentRow.Cells[0].Value.ToString());//也可以通过SetAttribute来增加一个属性
selectXe.GetElementsByTagName("title").Item(0).InnerText = dataGridView1.CurrentRow.Cells[2].Value.ToString();
selectXe.GetElementsByTagName("author").Item(0).InnerText =dataGridView1.CurrentRow.Cells[3].Value.ToString();
selectXe.GetElementsByTagName("price").Item(0).InnerText = dataGridView1.CurrentRow.Cells[4].Value.ToString();
doc.Save(@"Books.xml");
MessageBox.Show("数据已修改");
}
(二)设计性实验
1. 建立如下界面的的4个字段的XML文档格式。并写出插入记录的事件代码(记录插入到XML文档中)