对于XML
想必各位都比较了解
我也就不用费笔墨来描述它是什么了
我想在未来的Web开发中XML一定会大放异彩
XML是可扩展标记语言
使用它企业可以制定一套自己的数据格式
数据按照这种格式在网络中传输然后再通过XSLT将数据转换成用户期望的样子表示出来
这样便轻易的解决了数据格式不兼容的问题
用于Internet的数据传输
我想
这是XML对于我们这些程序员最诱人的地方!
我们今天的主题不是论述XML的好处而是讨论在C#中如何使用XML下面我们来了解一下使用程序访问XML的一些基础理论知识
访问的两种模型
在程序中访问进而操作XML文件一般有两种模型分别是使用DOM(文档对象模型)和流模型使用DOM的好处在于它允许编辑和更新XML文档可以随机访问文档中的数据可以使用XPath查询但是DOM的缺点在于它需要一次性的加载整个文档到内存中对于大型的文档这会造成资源问题流模型很好的解决了这个问题因为它对XML文件的访问采用的是流的概念也就是说任何时候在内存中只有当前节点但它也有它的不足它是只读的仅向前的不能在文档中执行向后导航操作虽然是各有千秋但我们也可以在程序中两者并用实现优劣互补嘛呵呵这是题外话了!我们今天主要讨论XML的读取那我们就详细讨论一下流模型吧!
流模型中的变体
流模型每次迭代XML文档中的一个节点适合于处理较大的文档所耗内存空间小流模型中有两种变体——推模型和拉模型
推模型也就是常说的SAXSAX是一种靠事件驱动的模型也就是说它每发现一个节点就用推模型引发一个事件而我们必须编写这些事件的处理程序这样的做法非常的不灵活也很麻烦
NET中使用的是基于拉模型的实现方案拉模型在遍历文档时会把感兴趣的文档部分从读取器中拉出不需要引发事件允许我们以编程的方式访问文档这大大的提高了灵活性在性能上拉模型可以选择性的处理节点而SAX每发现一个节点都会通知客户机从而使用拉模型可以提高Application的整体效率在NET中拉模型是作为XmlReader类实现的下面看一下该类的继承结构
我们今天来讲一下该体系结构中的XmlTextReader类该类提供对Xml文件进行读取的功能它可以验证文档是否格式良好如果不是格式良好的Xml文档该类在读取过程中将会抛出XmlException异常可使用该类提供的一些方法对文档节点进行读取筛选等操作以及得到节点的名称和值请牢记XmlTextReader是基于流模型的实现打个不恰当的比喻XML文件就好象水源闸一开水就流出流过了就流过了不会也不可以往回流内存中任何时候只有当前节点你可以使用XmlTextReader类的Read()方法读取下一个节点好了说了这么多来看一个例子编程要注重实际对吧看代码前先看下运行效果吧!
Example按纽遍历文档读取数据ExampleExample按纽得到节点类型Example过滤文档只获得数据内容Example得到属性节点Example按纽得到命名空间Example显示整个XML文档为此我专门写一个类来封装以上功能该类代码如下
//
//XmlReader类用于Xml文件的一般读取操作以下对这个类做简单介绍
//
//Attributes(属性):
//listBox: 设置该属性主要为了得到客户端控件以便于显示所读到的文件的内容(这里是ListBox控件)
//xmlPath: 设置该属性为了得到一个确定的Xml文件的绝对路径
//
//Basilic Using(重要的引用):
//SystemXml: 该命名空间中封装有对Xml进行操作的常用类本类中使用了其中的XmlTextReader类
//XmlTextReader: 该类提供对Xml文件进行读取的功能它可以验证文档是否格式良好如果不是格式 // 良好的Xml文档该类在读取过程中将会抛出XmlException异常可使用该类提供的
// 一些方法对文档节点进行读取筛选等操作以及得到节点的名称和值
//
//bool XmlTextReaderRead(): 读取流中下一个节点当读完最后一个节点再次调用该方法该方法返回false
//XmlNodeType XmlTextReaderNodeType: 该属性返回当前节点的类型
// XmlNodeTypeElement 元素节点
// XmlNodeTypeEndElement 结尾元素节点
// XmlNodeTypeXmlDeclaration 文档的第一个节点
// XmlNodeTypeText 文本节点
//bool XmlTextReaderHasAttributes: 当前节点有没有属性返回true或false
//string XmlTextReaderName: 返回当前节点的名称
//string XmlTextReaderValue: 返回当前节点的值
//string XmlTextReaderLocalName: 返回当前节点的本地名称
//string XmlTextReaderNamespaceURI: 返回当前节点的命名空间URI
//string XmlTextReaderPrefix: 返回当前节点的前缀
//bool XmlTextReaderMoveToNextAttribute(): 移动到当前节点的下一个属性
//
namespace XMLReading
{
using System;
using SystemXml;
using SystemWindowsForms;
using SystemComponentModel;
/// <summary>
/// Xml文件读取器
/// </summary>
public class XmlReader : IDisposable
{
private string _xmlPath;
private const string _errMsg = Error Occurred While Reading ;
private ListBox _listBox;
private XmlTextReader xmlTxtRd;
#region XmlReader 的构造器
public XmlReader()
{
this_xmlPath = stringEmpty;
this_listBox = null;
thisxmlTxtRd = null;
}
/// <summary>
/// 构造器
/// </summary>
/// <param name=_xmlPath>xml文件绝对路径</param>
/// <param name=_listBox>列表框用于显示xml</param>
public XmlReader(string _xmlPath ListBox _listBox)
{
this_xmlPath = _xmlPath;
this_listBox = _listBox;
thisxmlTxtRd = null;
}
#endregion
#region XmlReader 的资源释放方法
/// <summary>
/// 清理该对象所有正在使用的资源
/// </summary>
public void Dispose()
{
thisDispose(true);
GCSuppressFinalize(this);
}
/// <summary>
/// 释放该对象的实例变量
/// </summary>
/// <param name=disposing></param>
protected virtual void Dispose(bool disposing)
{
if (!disposing)
return;
if (thisxmlTxtRd != null)
{
thisxmlTxtRdClose();
thisxmlTxtRd = null;
}
if (this_xmlPath != null)
{
this_xmlPath = null;
}
}
#endregion
#region XmlReader 的属性
/// <summary>
/// 获取或设置列表框用于显示xml
/// </summary>
public ListBox listBox
{
get
{
return this_listBox;
}
set
{
this_listBox = value;
}
}
/// <summary>
/// 获取或设置xml文件的绝对路径
/// </summary>
public string xmlPath
{
get
{
return this_xmlPath;
}
set
{
this_xmlPath = value;
}
}
#endregion
/// <summary>
/// 遍历Xml文件
/// </summary>
public void EachXml()
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
this_listBoxItemsAdd(thisxmlTxtRdValue);
}
}
catch(XmlException exp)
{
throw new XmlException(_errMsg + this_xmlPath + expToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 读取Xml文件的节点类型
/// </summary>
public void ReadXmlByNodeType()
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
this_listBoxItemsAdd(thisxmlTxtRdNodeTypeToString());
}
}
catch(XmlException exp)
{
throw new XmlException(_errMsg + this_xmlPath + expToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 根据节点类型过滤Xml文档
/// </summary>
/// <param name=xmlNType>XmlNodeType 节点类型的数组</param>
public void FilterByNodeType(XmlNodeType[] xmlNType)
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
for (int i = ; i < xmlNTypeLength; i++)
{
if (xmlTxtRdNodeType == xmlNType[i])
{
this_listBoxItemsAdd(xmlTxtRdName + is Type + xmlTxtRdNodeTypeToString());
}
}
}
}
catch(XmlException exp)
{
throw new XmlException(_errMsg + thisxmlPath + expToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 读取Xml文件的所有文本节点值
/// </summary>
public void ReadXmlTextValue()
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
if (xmlTxtRdNodeType == XmlNodeTypeText)
{
this_listBoxItemsAdd(xmlTxtRdValue);
}
}
}
catch(XmlException xmlExp)
{
throw new XmlException(_errMsg + this_xmlPath + xmlExpToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 读取Xml文件的属性
/// </summary>
public void ReadXmlAttributes()
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
if (xmlTxtRdNodeType == XmlNodeTypeElement)
{
if (xmlTxtRdHasAttributes)
{
this_listBoxItemsAdd(The Element + xmlTxtRdName + has + xmlTxtRdAttributeCount + Attributes);
this_listBoxItemsAdd(The Attributes are:);
while(xmlTxtRdMoveToNextAttribute())
{
this_listBoxItemsAdd(xmlTxtRdName + = + xmlTxtRdValue);
}
}
else
{
this_listBoxItemsAdd(The Element + xmlTxtRdName + has no Attribute);
}
this_listBoxItemsAdd();
}
}
}
catch(XmlException xmlExp)
{
throw new XmlException(_errMsg + this_xmlPath + xmlExpToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 读取Xml文件的命名空间
/// </summary>
public void ReadXmlNamespace()
{
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
if (xmlTxtRdNodeType == XmlNodeTypeElement && xmlTxtRdPrefix != )
{
this_listBoxItemsAdd(The Prefix + xmlTxtRdPrefix + is associated with namespace + xmlTxtRdNamespaceURI);
this_listBoxItemsAdd(The Element with the local name + xmlTxtRdLocalName + is associated with + the namespace + xmlTxtRdNamespaceURI);
}
if (xmlTxtRdNodeType == XmlNodeTypeElement && xmlTxtRdHasAttributes)
{
while(xmlTxtRdMoveToNextAttribute())
{
if (xmlTxtRdPrefix != )
{
this_listBoxItemsAdd(The Prefix + xmlTxtRdPrefix + is associated with namespace + xmlTxtRdNamespaceURI);
this_listBoxItemsAdd(The Attribute with the local name + xmlTxtRdLocalName + is associated with the namespace + xmlTxtRdNamespaceURI);
}
}
}
}
}
catch(XmlException xmlExp)
{
throw new XmlException(_errMsg + this_xmlPath + xmlExpToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
/// <summary>
/// 读取整个Xml文件
/// </summary>
public void ReadXml()
{
string attAndEle = stringEmpty;
this_listBoxItemsClear();
thisxmlTxtRd = new XmlTextReader(this_xmlPath);
try
{
while(xmlTxtRdRead())
{
if (xmlTxtRdNodeType == XmlNodeTypeXmlDeclaration)
this_listBoxItemsAdd(stringFormat(<?{} {} ?>xmlTxtRdNamexmlTxtRdValue));
else if (xmlTxtRdNodeType == XmlNodeTypeElement)
{
attAndEle = stringFormat(<{} xmlTxtRdName);
if (xmlTxtRdHasAttributes)
{
while(xmlTxtRdMoveToNextAttribute())
{
attAndEle = attAndEle + stringFormat({}={} xmlTxtRdNamexmlTxtRdValue);
}
}
attAndEle = attAndEleTrim() + >;
this_listBoxItemsAdd(attAndEle);
}
else if (xmlTxtRdNodeType == XmlNodeTypeEndElement)
this_listBoxItemsAdd(stringFormat(</{}>xmlTxtRdName));
else if (xmlTxtRdNodeType == XmlNodeTypeText)
this_listBoxItemsAdd(xmlTxtRdValue);
}
}
catch(XmlException xmlExp)
{
throw new XmlException(_errMsg + this_xmlPath + xmlExpToString());
}
finally
{
if (thisxmlTxtRd != null)
thisxmlTxtRdClose();
}
}
}
}
窗体代码如下
namespace XMLReading
{
using System;
using SystemDrawing;
using SystemCollections;
using SystemComponentModel;
using SystemWindowsForms;
using SystemData;
using SystemXml;
public class Form : SystemWindowsFormsForm
{
private SystemWindowsFormsListBox listBox;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private SystemWindowsFormsButton button;
private string xmlPath;
private XmlReader xRead;
/// <summary>
/// 必需的设计器变量
/// </summary>
private SystemComponentModelContainer components = null;
public Form()
{
InitializeComponent();
}
/// <summary>
/// 清理所有正在使用的资源
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
componentsDispose();
}
}
baseDispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 不要使用代码编辑器修改
/// 此方法的内容
/// </summary>
private void InitializeComponent()
{
thislistBox = new SystemWindowsFormsListBox();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisbutton = new SystemWindowsFormsButton();
thisSuspendLayout();
//
// listBox
//
thislistBoxAnchor = ((SystemWindowsFormsAnchorStyles)((((SystemWindowsFormsAnchorStylesTop | SystemWindowsFormsAnchorStylesBottom)
| SystemWindowsFormsAnchorStylesLeft)
| SystemWindowsFormsAnchorStylesRight)));
thislistBoxItemHeight = ;
thislistBoxLocation = new SystemDrawingPoint( );
thislistBoxName = listBox;
thislistBoxSize = new SystemDrawingSize( );
thislistBoxTabIndex = ;
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesRight)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// button
//
thisbuttonAnchor = ((SystemWindowsFormsAnchorStyles)((SystemWindowsFormsAnchorStylesBottom | SystemWindowsFormsAnchorStylesLeft)));
thisbuttonLocation = new SystemDrawingPoint( );
thisbuttonName = button;
thisbuttonTabIndex = ;
thisbuttonText = Example;
thisbuttonClick += new SystemEventHandler(thisbutton_Click);
//
// Form
//
thisAutoScaleBaseSize = new SystemDrawingSize( );
thisClientSize = new SystemDrawingSize( );
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thisbutton);
thisControlsAdd(thislistBox);
thisName = Form;
thisText = XMLReader;
thisResumeLayout(false);
//
// xmlPath
//
thisxmlPath = samplexml;
}
#endregion
/// <summary>
/// 应用程序的主入口点
/// </summary>
[STAThread]
static void Main()
{
ApplicationRun(new Form());
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPaththislistBox);
try
{
xReadEachXml();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPaththislistBox);
try
{
xReadReadXmlByNodeType();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
XmlNodeType[] xmlNType = {XmlNodeTypeElement XmlNodeTypeEndElement XmlNodeTypeXmlDeclaration};
xRead = new XmlReader(thisxmlPath thislistBox);
try
{
xReadFilterByNodeType(xmlNType);
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPath thislistBox);
try
{
xReadReadXmlTextValue();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPath thislistBox);
try
{
xReadReadXmlAttributes();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPath thislistBox);
try
{
xReadReadXmlNamespace();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
private void button_Click(object sender SystemEventArgs e)
{
xRead = new XmlReader(thisxmlPath thislistBox);
try
{
xReadReadXml();
}
catch(XmlException xmlExp)
{
MessageBoxShow(xmlExpToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
catch(Exception exp)
{
MessageBoxShow(expToString()ErrorMessageBoxButtonsOKMessageBoxIconError);
}
finally
{
xReadDispose();
}
}
}
}
以下是用于测试的XML文件
在项目中新建一个XML文件取名为samplexml建好后把该文件拷到项目的bin目录下的Debug目录下
<?xml version= encoding=utf ?>
<Invoices date=// xmlns:cat=uri:BusinessCategories>
<customers custname=Chile Wines Inc phone= email= custid= delivery=international offerID=>
<cat:businfo>Wine Division South</cat:businfo>
<cat:businfo>Beer Division North</cat:businfo>
<order orderID=OID batchid=>
<details>
<items cat:num=>
<item>Rancagua While</item>
<item>Rancagua Red</item>
</items>
</details>
</order>
<order orderID=OID>
<details>
<items num=>
<item>Chillan Red</item>
<item>Rancagua While</item>
<item>Santiago Red</item>
<item>Rancagua While</item>
<item>Rancagua Red</item>
</items>
</details>
</order>
<order orderID=OID batchid=>
<details>
<items num=>
<item>Rancegao Red</item>
<item>Sutothad Black</item>
<item>BlackNme Blue</item>
<item>Booklist Red</item>
<item>Rancegao White</item>
</items>
</details>
</order>
</customers>
</Invoices>