对于xml,想必各位都比较了解,我也就不用费笔墨来描述它是什么了,我想在未来的web开发中xml一定会大放异彩,xml是可扩展标记语言,使用它企业可以制定一套自己的数据格式,数据按照这种格式在网络中传输然后再通过xslt将数据转换成用户期望的样子表示出来,这样便轻易的解决了数据格式不兼容的问题。用于internet的数据传输,我想,这是xml对于我们这些程序员最诱人的地方!
我们今天的主题不是论述xml的好处,而是讨论在c#中如何使用xml。下面我们来了解一下使用程序访问xml的一些基础理论知识。
访问的两种模型:
在程序中访问进而操作xml文件一般有两种模型,分别是使用dom(文档对象模型)和流模型,使用dom的好处在于它允许编辑和更新xml文档,可以随机访问文档中的数据,可以使用xpath查询,但是,dom的缺点在于它需要一次性的加载整个文档到内存中,对于大型的文档,这会造成资源问题。流模型很好的解决了这个问题,因为它对xml文件的访问采用的是流的概念,也就是说,任何时候在内存中只有当前节点,但它也有它的不足,它是只读的,仅向前的,不能在文档中执行向后导航操作。虽然是各有千秋,但我们也可以在程序中两者并用实现优劣互补嘛,呵呵,这是题外话了!我们今天主要讨论xml的读取,那我们就详细讨论一下流模型吧!
流模型中的变体:
流模型每次迭代xml文档中的一个节点,适合于处理较大的文档,所耗内存空间小。流模型中有两种变体——“推”模型和“拉”模型。
推模型也就是常说的sax,sax是一种靠事件驱动的模型,也就是说:它每发现一个节点就用推模型引发一个事件,而我们必须编写这些事件的处理程序,这样的做法非常的不灵活,也很麻烦。
.net中使用的是基于“拉”模型的实现方案,“拉”模型在遍历文档时会把感兴趣的文档部分从读取器中拉出,不需要引发事件,允许我们以编程的方式访问文档,这大大的提高了灵活性,在性能上“拉”模型可以选择性的处理节点,而sax每发现一个节点都会通知客户机,从而,使用“拉”模型可以提高application的整体效率。在.net中“拉”模型是作为xmlreader类实现的,下面看一下该类的继承结构:
我们今天来讲一下该体系结构中的xmltextreader类,该类提供对xml文件进行读取的功能,它可以验证文档是否格式良好,如果不是格式良好的xml文档,该类在读取过程中将会抛出xmlexception异常,可使用该类提供的一些方法对文档节点进行读取,筛选等操作以及得到节点的名称和值,请牢记:xmltextreader是基于流模型的实现,打个不恰当的比喻,xml文件就好象水源,闸一开水就流出,流过了就流过了不会也不可以往回流。内存中任何时候只有当前节点,你可以使用xmltextreader类的read()方法读取下一个节点。好了,说了这么多来看一个例子,编程要注重实际对吧。看代码前先看下运行效果吧!
example1按纽遍历文档读取数据,example2,example3按纽得到节点类型,example4过滤文档只获得数据内容,example5得到属性节点,example6按纽得到命名空间,example7显示整个xml文档,为此,我专门写一个类来封装以上功能,该类代码如下:
//—————————————————————————————————
//xmlreader类用于xml文件的一般读取操作,以下对这个类做简单介绍:
//
//attributes(属性):
//listbox: 设置该属性主要为了得到客户端控件以便于显示所读到的文件的内容(这里是listbox控件)
//xmlpath: 设置该属性为了得到一个确定的xml文件的绝对路径
//
//basilic using(重要的引用):
//system.xml: 该命名空间中封装有对xml进行操作的常用类,本类中使用了其中的xmltextreader类
//xmltextreader: 该类提供对xml文件进行读取的功能,它可以验证文档是否格式良好,如果不是格式
// 良好的xml文档,该类在读取过程中将会抛出xmlexception异常,可使用该类提供的
// 一些方法对文档节点进行读取,筛选等操作以及得到节点的名称和值
//
//bool xmltextreader.read(): 读取流中下一个节点,当读完最后一个节点再次调用该方法该方法返回false
//xmlnodetype xmltextreader.nodetype: 该属性返回当前节点的类型
// xmlnodetype.element 元素节点
// xmlnodetype.endelement 结尾元素节点
// xmlnodetype.xmldeclaration 文档的第一个节点
// xmlnodetype.text 文本节点
//bool xmltextreader.hasattributes: 当前节点有没有属性,返回true或false
//string xmltextreader.name: 返回当前节点的名称
//string xmltextreader.value: 返回当前节点的值
//string xmltextreader.localname: 返回当前节点的本地名称
//string xmltextreader.namespaceuri: 返回当前节点的命名空间uri
//string xmltextreader.prefix: 返回当前节点的前缀
//bool xmltextreader.movetonextattribute(): 移动到当前节点的下一个属性
//—————————————————————————————————
namespace xmlreading
{
using system;
using system.xml;
using system.windows.forms;
using system.componentmodel;
/// <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 = string.empty;
this._listbox = null;
this.xmltxtrd = 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;
this.xmltxtrd = null;
}
#endregion
#region xmlreader 的资源释放方法
/// <summary>
/// 清理该对象所有正在使用的资源
/// </summary>
public void dispose()
{
this.dispose(true);
gc.suppressfinalize(this);
}
/// <summary>
/// 释放该对象的实例变量
/// </summary>
/// <param name="disposing"></param>
protected virtual void dispose(bool disposing)
{
if (!disposing)
return;
if (this.xmltxtrd != null)
{
this.xmltxtrd.close();
this.xmltxtrd = 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._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
this._listbox.items.add(this.xmltxtrd.value);
}
}
catch(xmlexception exp)
{
throw new xmlexception(_errmsg + this._xmlpath + exp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 读取xml文件的节点类型
/// </summary>
public void readxmlbynodetype()
{
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
this._listbox.items.add(this.xmltxtrd.nodetype.tostring());
}
}
catch(xmlexception exp)
{
throw new xmlexception(_errmsg + this._xmlpath + exp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 根据节点类型过滤xml文档
/// </summary>
/// <param name="xmlntype">xmlnodetype 节点类型的数组</param>
public void filterbynodetype(xmlnodetype[] xmlntype)
{
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
for (int i = 0; i < xmlntype.length; i++)
{
if (xmltxtrd.nodetype == xmlntype[i])
{
this._listbox.items.add(xmltxtrd.name + " is type " + xmltxtrd.nodetype.tostring());
}
}
}
}
catch(xmlexception exp)
{
throw new xmlexception(_errmsg + this.xmlpath + exp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 读取xml文件的所有文本节点值
/// </summary>
public void readxmltextvalue()
{
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
if (xmltxtrd.nodetype == xmlnodetype.text)
{
this._listbox.items.add(xmltxtrd.value);
}
}
}
catch(xmlexception xmlexp)
{
throw new xmlexception(_errmsg + this._xmlpath + xmlexp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 读取xml文件的属性
/// </summary>
public void readxmlattributes()
{
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
if (xmltxtrd.nodetype == xmlnodetype.element)
{
if (xmltxtrd.hasattributes)
{
this._listbox.items.add("the element " + xmltxtrd.name + " has " + xmltxtrd.attributecount + " attributes");
this._listbox.items.add("the attributes are:");
while(xmltxtrd.movetonextattribute())
{
this._listbox.items.add(xmltxtrd.name + " = " + xmltxtrd.value);
}
}
else
{
this._listbox.items.add("the element " + xmltxtrd.name + " has no attribute");
}
this._listbox.items.add("");
}
}
}
catch(xmlexception xmlexp)
{
throw new xmlexception(_errmsg + this._xmlpath + xmlexp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 读取xml文件的命名空间
/// </summary>
public void readxmlnamespace()
{
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
if (xmltxtrd.nodetype == xmlnodetype.element && xmltxtrd.prefix != "")
{
this._listbox.items.add("the prefix " + xmltxtrd.prefix + " is associated with namespace " + xmltxtrd.namespaceuri);
this._listbox.items.add("the element with the local name " + xmltxtrd.localname + " is associated with" + " the namespace " + xmltxtrd.namespaceuri);
}
if (xmltxtrd.nodetype == xmlnodetype.element && xmltxtrd.hasattributes)
{
while(xmltxtrd.movetonextattribute())
{
if (xmltxtrd.prefix != "")
{
this._listbox.items.add("the prefix " + xmltxtrd.prefix + " is associated with namespace " + xmltxtrd.namespaceuri);
this._listbox.items.add("the attribute with the local name " + xmltxtrd.localname + " is associated with the namespace " + xmltxtrd.namespaceuri);
}
}
}
}
}
catch(xmlexception xmlexp)
{
throw new xmlexception(_errmsg + this._xmlpath + xmlexp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
/// <summary>
/// 读取整个xml文件
/// </summary>
public void readxml()
{
string attandele = string.empty;
this._listbox.items.clear();
this.xmltxtrd = new xmltextreader(this._xmlpath);
try
{
while(xmltxtrd.read())
{
if (xmltxtrd.nodetype == xmlnodetype.xmldeclaration)
this._listbox.items.add(string.format("<?{0} {1} ?>",xmltxtrd.name,xmltxtrd.value));
else if (xmltxtrd.nodetype == xmlnodetype.element)
{
attandele = string.format("<{0} ",xmltxtrd.name);
if (xmltxtrd.hasattributes)
{
while(xmltxtrd.movetonextattribute())
{
attandele = attandele + string.format("{0}={1} ",xmltxtrd.name,xmltxtrd.value);
}
}
attandele = attandele.trim() + ">";
this._listbox.items.add(attandele);
}
else if (xmltxtrd.nodetype == xmlnodetype.endelement)
this._listbox.items.add(string.format("</{0}>",xmltxtrd.name));
else if (xmltxtrd.nodetype == xmlnodetype.text)
this._listbox.items.add(xmltxtrd.value);
}
}
catch(xmlexception xmlexp)
{
throw new xmlexception(_errmsg + this._xmlpath + xmlexp.tostring());
}
finally
{
if (this.xmltxtrd != null)
this.xmltxtrd.close();
}
}
}
}
窗体代码如下:
namespace xmlreading
{
using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.data;
using system.xml;
public class form1 : system.windows.forms.form
{
private system.windows.forms.listbox listbox1;
private system.windows.forms.button button1;
private system.windows.forms.button button2;
private system.windows.forms.button button3;
private system.windows.forms.button button4;
private system.windows.forms.button button5;
private system.windows.forms.button button6;
private system.windows.forms.button button7;
private string xmlpath;
private xmlreader xread;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private system.componentmodel.container components = null;
public form1()
{
initializecomponent();
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
#region windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.listbox1 = new system.windows.forms.listbox();
this.button1 = new system.windows.forms.button();
this.button2 = new system.windows.forms.button();
this.button3 = new system.windows.forms.button();
this.button4 = new system.windows.forms.button();
this.button5 = new system.windows.forms.button();
this.button6 = new system.windows.forms.button();
this.button7 = new system.windows.forms.button();
this.suspendlayout();
//
// listbox1
//
this.listbox1.anchor = ((system.windows.forms.anchorstyles)((((system.windows.forms.anchorstyles.top | system.windows.forms.anchorstyles.bottom)
| system.windows.forms.anchorstyles.left)
| system.windows.forms.anchorstyles.right)));
this.listbox1.itemheight = 12;
this.listbox1.location = new system.drawing.point(8, 8);
this.listbox1.name = "listbox1";
this.listbox1.size = new system.drawing.size(716, 460);
this.listbox1.tabindex = 0;
//
// button1
//
this.button1.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button1.location = new system.drawing.point(8, 488);
this.button1.name = "button1";
this.button1.tabindex = 1;
this.button1.text = "example1";
this.button1.click += new system.eventhandler(this.button1_click);
//
// button2
//
this.button2.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button2.location = new system.drawing.point(96, 488);
this.button2.name = "button2";
this.button2.tabindex = 2;
this.button2.text = "example2";
this.button2.click += new system.eventhandler(this.button2_click);
//
// button3
//
this.button3.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.right)));
this.button3.location = new system.drawing.point(648, 488);
this.button3.name = "button3";
this.button3.tabindex = 3;
this.button3.text = "example7";
this.button3.click += new system.eventhandler(this.button3_click);
//
// button4
//
this.button4.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button4.location = new system.drawing.point(184, 488);
this.button4.name = "button4";
this.button4.tabindex = 4;
this.button4.text = "example3";
this.button4.click += new system.eventhandler(this.button4_click);
//
// button5
//
this.button5.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button5.location = new system.drawing.point(272, 488);
this.button5.name = "button5";
this.button5.tabindex = 5;
this.button5.text = "example4";
this.button5.click += new system.eventhandler(this.button5_click);
//
// button6
//
this.button6.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button6.location = new system.drawing.point(360, 488);
this.button6.name = "button6";
this.button6.tabindex = 6;
this.button6.text = "example5";
this.button6.click += new system.eventhandler(this.button6_click);
//
// button7
//
this.button7.anchor = ((system.windows.forms.anchorstyles)((system.windows.forms.anchorstyles.bottom | system.windows.forms.anchorstyles.left)));
this.button7.location = new system.drawing.point(448, 488);
this.button7.name = "button7";
this.button7.tabindex = 7;
this.button7.text = "example6";
this.button7.click += new system.eventhandler(this.button7_click);
//
// form1
//
this.autoscalebasesize = new system.drawing.size(6, 14);
this.clientsize = new system.drawing.size(728, 517);
this.controls.add(this.button7);
this.controls.add(this.button6);
this.controls.add(this.button5);
this.controls.add(this.button4);
this.controls.add(this.button3);
this.controls.add(this.button2);
this.controls.add(this.button1);
this.controls.add(this.listbox1);
this.name = "form1";
this.text = "xmlreader";
this.resumelayout(false);
//
// xmlpath
//
this.xmlpath = "sample.xml";
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[stathread]
static void main()
{
application.run(new form1());
}
private void button1_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath,this.listbox1);
try
{
xread.eachxml();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button2_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath,this.listbox1);
try
{
xread.readxmlbynodetype();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button3_click(object sender, system.eventargs e)
{
xmlnodetype[] xmlntype = {xmlnodetype.element, xmlnodetype.endelement, xmlnodetype.xmldeclaration};
xread = new xmlreader(this.xmlpath, this.listbox1);
try
{
xread.filterbynodetype(xmlntype);
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button4_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath, this.listbox1);
try
{
xread.readxmltextvalue();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button5_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath, this.listbox1);
try
{
xread.readxmlattributes();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button6_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath, this.listbox1);
try
{
xread.readxmlnamespace();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
private void button7_click(object sender, system.eventargs e)
{
xread = new xmlreader(this.xmlpath, this.listbox1);
try
{
xread.readxml();
}
catch(xmlexception xmlexp)
{
messagebox.show(xmlexp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
catch(exception exp)
{
messagebox.show(exp.tostring(),"error",messageboxbuttons.ok,messageboxicon.error);
}
finally
{
xread.dispose();
}
}
}
}
以下是用于测试的xml文件:
在项目中新建一个xml文件取名为sample.xml,建好后把该文件拷到项目的bin目录下的debug目录下
<?xml version="1.0" encoding="utf-8" ?>
<invoices date="28/11/2001" xmlns:cat="uri:business-categories">
<customers custname="chile wines inc" phone="1241 923 56332" email="cw@yahoo.com.cn" custid="192398" delivery="international" offerid="27">
<cat:businfo>wine division south</cat:businfo>
<cat:businfo>beer division north</cat:businfo>
<order orderid="oid921" batchid="123">
<details>
<items cat:num="2">
<item>rancagua while</item>
<item>rancagua red</item>
</items>
</details>
</order>
<order orderid="oid927">
<details>
<items num="5">
<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="oid931" batchid="123">
<details>
<items num="6">
<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>
