以文本方式查看主题 - 中文XML论坛 - 专业的XML技术讨论区 (http://bbs.xml.org.cn/index.asp) -- 『 Dot NET,C#,ASP,VB 』 (http://bbs.xml.org.cn/list.asp?boardid=43) ---- 在Visual C#中使用XML指南之读取 (http://bbs.xml.org.cn/dispbbs.asp?boardid=43&rootid=&id=15055) |
-- 作者:卷积内核 -- 发布时间:3/4/2005 11:13:00 AM -- 在Visual C#中使用XML指南之读取 对于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文档,为此,我专门写一个类来封装以上功能,该类代码如下: namespace XMLReading /// <summary> public class XmlReader : IDisposable #region XmlReader 的构造器 public XmlReader() /// <summary> public XmlReader(string _xmlPath, ListBox _listBox) #endregion /// <summary> /// </summary> public void Dispose() /// <summary> protected virtual void Dispose(bool disposing) if (this._xmlPath != null) #endregion /// <summary> public ListBox listBox /// <summary> public string xmlPath #endregion /// <summary> public void EachXml() try /// <summary> public void ReadXmlByNodeType() try /// <summary> public void FilterByNodeType(XmlNodeType[] xmlNType) /// <summary> /// </summary> public void ReadXmlTextValue() try /// <summary> public void ReadXmlAttributes() try this._listBox.Items.Add("The Attributes are:"); while(xmlTxtRd.MoveToNextAttribute()) /// <summary> public void ReadXmlNamespace() 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) this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI); } /// <summary> public void ReadXml() try attAndEle = attAndEle.Trim() + ">"; 窗体代码如下: 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> |
W 3 C h i n a ( since 2003 ) 旗 下 站 点 苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》 |
109.863ms |