设为首页收藏本站language 语言切换
查看: 1582|回复: 0
收起左侧

解析.Net框架下的XML编程技术

[复制链接]
发表于 2010-2-25 10:28:56 | 显示全部楼层 |阅读模式
<p ><b><b><font color="#CC0000"></font></b>一.前言:</b><p >XML是微软.Net战略的一个重要组成部分,而且它可谓是XML Web服务的基石,所以掌握.Net框架下的XML技术自然显得非常重要了。本文将指导大家如何运用C#语言完成.Net框架下的XML文档的读写操作。首先,我会向大家介绍.Net框架中与XML相关的命名空间和其中的重要类。其次,我还会给出有关的实例以使读者更进一步的了解XML文档的读写操作的具体方法。<p ><p ><b>二.XML命名空间和相关类简介:</b><p >在深入进行.Net框架下的XML文档的操作之前,我想很有必要向大家介绍.Net框架中与XML技术有关的命名空间和其中一些重要的类。.Net框架为我们提供了以下一些命名空间:System.Xml、System.Xml.Schema、System.Xml.Serialization、System.Xml.Xpath以及 System.Xml.Xsl来包容和XML操作相关的类。<p >System.Xml命名空间包含了一些最重要的XML类,其中最主要的类是和XML文档的读写操作相关的类。这些类中包括4个与读相关的类以及2个与写相关的类。它们分别是:XmlReader、XmlTextReader、XmlValidatingReader、XmlNodeReader、XmlWriter以及 XmlTextWriter。本文将重点介绍这些类,因为它们是最基本也是最重要的类。<p >XmlReader类是一个虚基类,它包含了读XML文档的方法和属性。该类中的Read方法是一个基本的读XML文档的方法,它以流形式读取XML文档中的节点(Node)。另外,该类还提供了ReadString、ReadInnerXml、ReadOuterXml和ReadStartElement等更高级的读方法。除了提供读XML文档的方法外,XmlReader类还为程序员提供了MoveToAttribute、MoveToFirstAttribute、MoveToContent、MoveToFirstContent、MoveToElement以及 MoveToNextAttribute等具有导航功能的方法。在本文后面介绍的实例中,我们将运用到这些方法。<p >XmlTextReader、XmlNodeReader以及XmlValidatingReader等类是从XmlReader类继承过来的子类。根据它们的名称,我们可以知道其作用分别是读取文本内容、读取节点和读取XML模式(Schemas)。<p >XmlWriter类为程序员提供了许多写XML文档的方法,它是XmlTextWriter类的基类,我在后面的实例中会给出相关的运用方法。<p >XmlNode类是一个非常重要的类,它代表了XML文档中的某个节点。该节点可以是XML文档的根节点,这样它就代表整个XML文档了。它是许多很有用的类的基类,这些类包括插入节点的类、删除节点的类、替换节点的类以及在XML文档中完成导航功能的类。同时,XmlNode类还为程序员提供了获取双亲节点、子节点、最后一个子节点、节点名称以及节点类型等的属性。它的三个最主要的子类包括:XmlDocument、XmlDataDocument以及XmlDocumentFragment。XmlDocument类代表了一个XML文档,它提供了载入和保存XML文档的方法和属性。这些方法包括了Load、LoadXml和Save等。同时,它还提供了添加特性(Attributes)、说明(Comments)、空间(Spaces)、元素(Elements)和新节点(New Nodes)等XML项的功能。XmlDocumentFragment类代表了一部分XML文档,它能被用来添加到其他的XML文档中。XmlDataDocument类可以让程序员更好地完成和ADO.NET中的数据集对象之间的互操作。<p >除了上面介绍的System.Xml命名空间中的类外,该命名空间还包括了XmlConvert、XmlLinkedNode以及XmlNodeList等类,不过这些类不是本文介绍的重点,有兴趣的读者不妨去参考相关文档资料。<p >System.Xml.Schema命名空间中包含了和XML模式相关的类,这些类包括XmlSchema、XmlSchemaAll、XmlSchemaXPath以及XmlSchemaType等类。<p >System.Xml.Serialization命名空间中包含了和XML文档的序列化和反序列化操作相关的类,XML文档的序列化操作能将XML格式的数据转化为流格式的数据并能在网络中传输,而反序列化则完成相反的操作,即将流格式的数据还原成XML格式的数据。<p >System.Xml.XPath命名空间包含了XPathDocument、XPathExression、XPathNavigator以及XPathNodeIterator等类,这些类能完成XML文档的导航功能。在XPathDocument类的协助下,XPathNavigator类能完成快速的XML文档导航功能,该类为程序员提供了许多Move方法以完成导航功能。<p >System.Xml.Xsl命名空间中的类完成了XSLT的转换功能。<p ><p ><b>三.读XML文档的方法:</b><p >在介绍完.Net框架中和XML有关的命名空间和相关类后,我接着向大家介绍和XML相关的一些操作。首先,我向大家介绍的读取XML文档的方法。在下面的实例程序中,我将运用VS.net开发工具附带的"books.xml"文件来作为示例。你可以在你的机器上搜索到该文件(或请参考附录),或者你也可以运用其他的XML文件。<p >首先,我们用XmlTextReader类的对象来读取该XML文档。方法很简单,就是在创建新对象的构造函数中指明XML文件的位置即可。<p >XmlTextReader textReader = new XmlTextReader("C:\\books.xml");<p >一旦新对象创建完毕,你就可以调用其Read方法来读取XML文档了。调用Read方法之后,信息被存储起来,你可以通过读取该对象的Name、BaseURI、Depth、LineNumber等属性来获取这些信息。下面我给出一个完整的实例,该实例通过简单的读取"books.xml"文件,然后将其中的信息显示在控制台中。<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>using System;using System.Xml;  namespace ReadXml{    class Class1    {        static void Main( string[] args )        {            // 创建一个XmlTextReader类的对象并调用Read方法来读取文件            XmlTextReader textReader  = new XmlTextReader(&quot;C:\\books.xml&quot;);            textReader.Read();            // 节点非空则执行循环体            while ( textReader.Read() )            {                // 读取第一个元素                textReader.MoveToElement();                Console.WriteLine(&quot;XmlTextReader Properties Test&quot;);                Console.WriteLine(&quot;===================&quot;);                  // 读取该元素的属性并显示在控制台中                Console.WriteLine(&quot;Name:&quot; + textReader.Name);                Console.WriteLine(&quot;Base URI:&quot; + textReader.BaseURI);                Console.WriteLine(&quot;Local Name:&quot; + textReader.LocalName);                Console.WriteLine(&quot;Attribute Count:&quot; + textReader.AttributeCount.ToString());                Console.WriteLine(&quot;Depth:&quot; + textReader.Depth.ToString());                Console.WriteLine(&quot;Line Number:&quot; + textReader.LineNumber.ToString());                Console.WriteLine(&quot;Node Type:&quot; + textReader.NodeType.ToString());                Console.WriteLine(&quot;Attribute Count:&quot; + textReader.Value.ToString());            }        }    }}</ccid_code></pre></td></tr></table></ccid_nobr><p >XmlTextReader类中有一个很重要的属性-NodeType,通过该属性,我们可以知道其节点的节点类型。而枚举类型XmlNodeType中包含了诸如Attribute、CDATA、Element、Comment、Document、DocumentType、Entity、ProcessInstruction以及WhiteSpace等的XML项的类型。通过与XmlNodeType中的元素的比较,我们可以获取相应节点的节点类型并对其完成相关的操作。下面我就给出一个实例,该实例读取每个节点的NodeType,并根据其节点类型显示其中的内容,同时程序还记录了XML文件中每种节点类型的数目。<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>using System;using System.Xml;  namespace ReadXML{    class Class2    {        static void Main( string[] args )        {            int ws = 0;            int pi = 0;            int dc = 0;            int cc = 0;            int ac = 0;            int et = 0;            int el = 0;            int xd = 0;              XmlTextReader textReader  = new XmlTextReader(&quot;C:\\books.xml&quot;);              while (textReader.Read())            {                XmlNodeType nType = textReader.NodeType;                // 节点类型为XmlDeclaration                if (nType == XmlNodeType.XmlDeclaration)                {                    Console.WriteLine(&quot;Declaration:&quot; + textReader.Name.ToString());                    xd = xd + 1;                }                           // 节点类型为Comment                if( nType == XmlNodeType.Comment)                {                    Console.WriteLine(&quot;Comment:&quot; + textReader.Name.ToString());                    cc = cc + 1;                }                           // 节点类型为Attribute                if( nType == XmlNodeType.Attribute)                {                    Console.WriteLine(&quot;Attribute:&quot; + textReader.Name.ToString());                    ac = ac + 1;                }                  // 节点类型为Element                if ( nType == XmlNodeType.Element)                {                    Console.WriteLine(&quot;Element:&quot; + textReader.Name.ToString());                    el = el + 1;                }                  // 节点类型为Entity                if ( nType == XmlNodeType.Entity )                {                    Console.WriteLine(&quot;Entity:&quot; + textReader.Name.ToString());                    et = et + 1;                }                           // 节点类型为Process Instruction                if( nType == XmlNodeType. ProcessInstruction )                {                    Console.WriteLine(&quotrocess Instruction:&quot; + textReader.Name.ToString());                    pi = pi + 1;                }                       // 节点类型为DocumentType                if( nType == XmlNodeType.DocumentType)                {                    Console.WriteLine(&quot;DocumentType:&quot; + textReader.Name.ToString());                    dc = dc + 1;                }                  // 节点类型为Whitespace                if ( nType == XmlNodeType.Whitespace )                {                    Console.WriteLine(&quot;WhiteSpace:&quot; + textReader.Name.ToString());                    ws = ws + 1;                }            }              // 在控制台中显示每种类型的数目            Console.WriteLine(&quot;Total Comments:&quot; + cc.ToString());            Console.WriteLine(&quot;Total Attributes:&quot; + ac.ToString());            Console.WriteLine(&quot;Total Elements:&quot; + el.ToString());            Console.WriteLine(&quot;Total Entity:&quot; + et.ToString());            Console.WriteLine(&quot;Total Process Instructions:&quot; + pi.ToString());            Console.WriteLine(&quot;Total Declaration:&quot; + xd.ToString());            Console.WriteLine(&quot;Total DocumentType:&quot; + dc.ToString());            Console.WriteLine(&quot;Total WhiteSpaces:&quot; + ws.ToString());        }    }}</ccid_code></pre></td></tr></table></ccid_nobr><p >以上,我向大家介绍了如何运用XmlTextReader类的对象来读取XML文档,并根据节点的NodeType属性来取得其节点类型信息。同时XmlReader这个基类还有XmlNodeReader和XmlValidatingReader等派生类,它们分别是用来读取XML文档的节点和模式的。限于篇幅,这里就不介绍了,读者可以参考有关资料。<p ><p ><b>四.写XML文档的方法:</b><p >XmlWriter类包含了写XML文档所需的方法和属性,它是XmlTextWriter类和XmlNodeWriter类的基类。该类包含了WriteNode、WriteString、WriteAttributes、WriteStartElement以及WriteEndElement等一系列写XML文档的方法,其中有些方法是成对出现的。比如你要写入一个元素,你首先得调用WriteStartElement方法,接着写入实际内容,最后是调用WriteEndElement方法以表示结束。该类还包含了WriteState、XmlLang和XmlSpace等属性,其中WriteState属性表明了写的状态。因为XmlWriter类包含了很多写XML文档的方法,所以这里只是介绍最主要的几种。下面我们通过其子类XmlTextWriter类来说明如何写XML文档。<p >首先,我们要创建一个XmlTextWriter类的实例对象。该类的构造函数XmlTextWriter有三种重载形式,其参数分别为一个字符串、一个流对象和一个TextWriter对象。这里我们运用字符串的参数形式,该字符串就指明了所要创建的XML文件的位置,方法如下:<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>XmlTextWriter textWriter = New XmlTextWriter(&quot;C:\\myXmFile.xml&quot;, null);</ccid_code></pre></td></tr></table></ccid_nobr><p >在创建完对象后,我们调用WriterStartDocument方法开始写XML文档,在完成写工作后,就调用WriteEndDocument结束写过程并调用Close方法将它关闭。在写的过程中,我们可以调用WriteComment方法来添加说明,通过调用WriteString方法来添加一个字符串,通过调用WriteStartElement和WriteEndElement方法对来添加一个元素,通过调用WriteStartAttribute和WriteEndAttribute方法对来添加一个属性。我们还可以通过调用WriteNode方法来添加整一个节点,其它的写的方法还包括WriteProcessingInstruction和WriteDocType等等。下面的实例就是介绍如何具体运用这些方法来完成XML文档的写工作的。<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>using System;using System.Xml;  namespace WriteXML{    class Class1    {        static void Main( string[] args )        {            // 创建XmlTextWriter类的实例对象            XmlTextWriter textWriter = new XmlTextWriter(&quot;C:\\myXmFile.xml&quot;, null);             // 开始写过程,调用WriteStartDocument方法            textWriter.WriteStartDocument();              // 写入说明            textWriter.WriteComment(&quot;First Comment XmlTextWriter Sample Example&quot;);            textWriter.WriteComment(&quot;myXmlFile.xml in root dir&quot;);               // 写入一个元素            textWriter.WriteStartElement(&quot;Name&quot;, &quot;&quot;);            textWriter.WriteString(&quot;Student&quot;);            textWriter.WriteEndElement();              // 再写入一个元素            textWriter.WriteStartElement(&quot;Address&quot;, &quot;&quot;);            textWriter.WriteString(&quot;Colony&quot;);            textWriter.WriteEndElement();              // 写入字符            char [] ch = new char[3];            ch[0] = 'a';            ch[1] = 'r';            ch[2] = 'c';            textWriter.WriteStartElement(&quot;Char&quot;);            textWriter.WriteChars(ch, 0, ch.Length);            textWriter.WriteEndElement();              // 写文档结束,调用WriteEndDocument方法            textWriter.WriteEndDocument();            // 关闭textWriter            textWriter.Close();        }    }}</ccid_code></pre></td></tr></table></ccid_nobr><p ><b>五.运用XmlDocument类:</b><p >XmlDocument类的对象代表了一个XML文档,它也是一个非常重要的XML类。该类包含了Load、LoadXml以及Save等重要的方法。其中Load方法可以从一个字符串指定的XML文件或是一个流对象、一个TextReader对象、一个XmlReader对象导入XML数据。LoadXml方法则完成从一个特定的XML文件导入XML数据的功能。它的Save方法则将XML数据保存到一个XML文件中或是一个流对象、一个TextWriter对象、一个XmlWriter对象中。<p >下面的程序中我们用到了XmlDocument类对象的LoadXml方法,它从一个XML文档段中读取XML数据并调用其Save方法将数据保存在一个文件中。<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>// 创建一个XmlDocument类的对象XmlDocument doc = new XmlDocument();doc.LoadXml((&quot;&lt;Student type='regular' Section='B'&gt;&lt;Name&gt;Tommy Lex&lt;/Name&gt;&lt;/Student&gt;&quot;));// 保存到文件中doc.Save(&quot;C:\\student.xml&quot;);</ccid_code></pre></td></tr></table></ccid_nobr><p >这里,我们还可以通过改变Save方法中参数,将XML数据显示在控制台中,方法如下:<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>doc.Save(Console.Out);</ccid_code></pre></td></tr></table></ccid_nobr><p >而在下面的程序中,我们用到了一个XmlTextReader对象,通过它我们读取"books.xml"文件中的XML数据。然后创建一个XmlDocument对象并载入XmlTextReader对象,这样XML数据就被读到XmlDocument对象中了。最后,通过该对象的Save方法将XML数据显示在控制台中。<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>XmlDocument doc = new XmlDocument();// 创建一个XmlTextReader对象,读取XML数据XmlTextReader reader = new XmlTextReader(&quot;c:\\books.xml&quot;);reader.Read();// 载入XmlTextReader类的对象doc.Load(reader);// 将XML数据显示在控制台中doc.Save(Console.Out);</ccid_code></pre></td></tr></table></ccid_nobr><p ><b>六.总结:</b><p >XML技术作为.Net的基石,其重要性自然不言而喻。.Net框架包含了五个命名空间和大量的类来支持与XML技术有关的操作。其中System.Xml是最重要的一个命名空间,其中的XmlReader类和XmlWriter类以及它们的派生类完成了XML文档的读写操作,是最基本也是最重要的类。XmlDocument类代表了XML文档,它能完成与整个XML文档相关的各类操作,同时和其相关的XmlDataDocument类也是非常重要的,值得读者的深入研究。<p ><p ><b>附录</b><p >"books.xml"文件如下:<p ><ccid_nobr><table width="550" border="1" cellspacing="0" cellpadding="2" bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center"><tr><td bgcolor="e6e6e6" class="code"><pre><ccid_code>&lt;?xml version='1.0'?&gt;&lt;!-- This file represents a fragment of a book store inventory database --&gt;&lt;bookstore&gt;  &lt;book genre=&quot;autobiography&quot; publicationdate=&quot;1981&quot; ISBN=&quot;1-861003-11-0&quot;&gt;    &lt;title&gt;The Autobiography of Benjamin Franklin&lt;/title&gt;    &lt;author&gt;      &lt;first-name&gt;Benjamin&lt;/first-name&gt;      &lt;last-name&gt;Franklin&lt;/last-name&gt;    &lt;/author&gt;    &lt;price&gt;8.99&lt;/price&gt;  &lt;/book&gt;  &lt;book genre=&quot;novel&quot; publicationdate=&quot;1967&quot; ISBN=&quot;0-201-63361-2&quot;&gt;    &lt;title&gt;The Confidence Man&lt;/title&gt;    &lt;author&gt;      &lt;first-name&gt;Herman&lt;/first-name&gt;      &lt;last-name&gt;Melville&lt;/last-name&gt;    &lt;/author&gt;    &lt;price&gt;11.99&lt;/price&gt;  &lt;/book&gt;  &lt;book genre=&quot;philosophy&quot; publicationdate=&quot;1991&quot; ISBN=&quot;1-861001-57-6&quot;&gt;    &lt;title&gt;The Gorgias&lt;/title&gt;    &lt;author&gt;      &lt;first-name&gt;Sidas&lt;/first-name&gt;      &lt;last-name&gtlato&lt;/last-name&gt;    &lt;/author&gt;    &lt;price&gt;9.99&lt;/price&gt;  &lt;/book&gt;&lt;/bookstore&gt;</ccid_code></pre></td></tr></table></ccid_nobr><p ><p ><center class="name02">(责任编辑 GUIDE)</center><p align="center"></p></p>
您需要登录后才可以回帖 登录 | 论坛注册

本版积分规则

QQ|Archiver|手机版|小黑屋|sitemap|鸿鹄论坛 ( 京ICP备14027439号 )  

GMT+8, 2025-4-8 18:12 , Processed in 0.921108 second(s), 24 queries , Redis On.  

  Powered by Discuz!

  © 2001-2025 HH010.COM

快速回复 返回顶部 返回列表