使用Csharp读写XML文档

原文地址:http://www.dingos.cn/index.php?topic=888.0


在这篇文章中将介绍如何在Microsoft .NET环境下使用C#语言来读写XML文档。首先将简要讨论Microsoft .NET Framework类库中的命名空间和主要类。然后读XML文档。最后将结束利用ADO.NET 和 XML .NET模型从关系型数据库读写XML文档。

【Microsoft .NET有关XML命名空间和类的介绍】
开始使用.NET框架对XML文档进行工作前,要知道在.NET运行库中提供有关的命名空间和类。.NET提供了5个命名空间 - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, 和 System.Xml.Xsl支持XML操作的类。
System.Xml命名空间包含了XML操作的主要类。这个命名空间中包含许多读写XML文档的类。在这篇文章中将集中介绍读写类。这些读写类用于读写XML文档。这些类是 - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, 和 XmlTextWriter.
XmlReader类是一个抽象基础类,并包含读取文件的方法和属性。Read方法用于读取流上的一个节点。这个类除了包含读节点功能还包含定位文档中节点的功能,例如MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement 和 MoveToNextAttribute等方法。ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement是其他的一些读方法。这个类还有一个Skip方法用于从当前节点跳转到下一个节点。将在下面的例子中使用这些方法。
XmlTextReader, XmlNodeReader 和 XmlValidatingReader类继承自XmlReader类。正如他们的名字解释,他们使用与读文本,节点和概要。
XmlWrite类包含了将数据写入XML文件的功能。这个类提供了许多写XML文档项目的方法。这个类XmlTextWriter类的基类,将在下面的例子中使用。
XmlNode类起着非常重要的作用。虽然这个类表示XML的单个节点但是也可以表示XML文档的根节点并描述这个文件。这个类是通过代位用于插入、移除、替换节点的抽象基类。这个类也包含了获得父节点,子节点,名称,最后子节点,节点类型等的属性。XmlDocument, XmlDataDocument 和 XmlDocumentFragment类是基础于XmlNode类的节点。XmlDocument类用于描述一个XML文档并提供了加载和保存文档的属性和方法。它也提供了加载XML项目如特性,注释,空格,元素,和新节点的功能。Load和LoadXml方法用于加载XML文档,Save方法用于各个文档。XmlDocumentFragment类用于描述一个文档的片段可用于添加文档。XmlDataDocument类提供了处理ADO.NET数据的方法和属性。
尽管上面描述了一些类,但System.Xml命名空间还包括更多的类。例如XmlConvert, XmlLinkedNode, 和 XmlNodeList。
下一个Xml系列的命名空间是System.Xml.Schema。这个类用于操作XML概要的类例如XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType。
System.Xml.Serialization命名空间包含将对象序列化到XML各式的文档或流中。
System.Xml.XPath命名空间包含与XPath相关的类用于使用XPath规范。这个命名空间包含以下的类 - XPathDocument, XPathExression, XPathNavigator, 和 XPathNodeIterator。XpathDocument, XpathNavigator具有通过XML文档定位的帮助。这些类包含许多Move方法用于遍历整个文档。
System.Xml.Xsl命名空间包含操作XSL/T转换的类。

【读XML文档】
在下面的示例中,使用XmlTextReader读文件“books.xml”变将数据显示。这个文件来自VS.NET自带示例中。可以搜索机器在下面语句中修改文件的路径:
XmlTextReader textReader   = new XmlTextReader("C://books.xml");

或可以使用其他任何XML文件。
XmlTextReader, XmlNodeReader 和 XmlValidatingReader类继承至XmlReader类。这些了除了XmlReader的属性方法外,其他类也包含读文本、节点、概要等成员。这里使用XmlTextReader类来读XML文件。可以通过构造方法将文件名作为参数传递。
XmlTextReader textReader   = new XmlTextReader("C://books.xml");

创建了XmlTextReader后,可以调用Read方法开始读取文档。调用read方法后,可以读取存储在文档中的所有数据和信息。XmlReader类有例如Name, BaseURI, Depth, LineNumber 等属性。

列表1读文档并显示这些属性的节点信息。
【示例1】在这个示例中使用XmlTextReader类调用Read方来来读取XML文件,一个节点一个节点的读取文件信息直到文件结束并将内容显示在控制台。
using System;
using System.Xml;

namespace ReadXml1{
      class Class1{
            static void Main(string[] args){
                  // Create an isntance of XmlTextReader and call Read method to read the file
                  XmlTextReader textReader   = new XmlTextReader("books.xml");
                  textReader.Read();
                  // If the node has value
                  while (textReader.Read()){
                        // Move to fist element
                        textReader.MoveToElement();
                        Console.WriteLine("XmlTextReader Properties Test");
                        Console.WriteLine("===================");

                        // Read this element's properties and display them on console
                        Console.WriteLine("Name:" + textReader.Name);
                        Console.WriteLine("Base URI:" + textReader.BaseURI);
                        Console.WriteLine("Local Name:" + textReader.LocalName);
                        Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
                        Console.WriteLine("Depth:" + textReader.Depth.ToString());
                        Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
                        Console.WriteLine("Node Type:" + textReader.NodeType.ToString());
                        Console.WriteLine("Attribute Count:" + textReader.Value.ToString());
                  }
                  Console.ReadLine();
            }
      }
}

当想知道文档内容的类型使用XmlTextReader类的NodeType属性是非常重要的。XmlNodeType枚举出XML项目成员的类型例如Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace等等。

列表2代码示例读XML文档查找节点的类型并将文档中各节点的类型显示。
【示例2】这个例子,使用XmlTextReader来读取XML文件,调用Read方法逐一读取节点知道文件结束。读取节点后,检查节点的NodeType属性找到节点并将节点内容显示在控制台并保存节点类型的路径数。最后显示文档中不同类型的节点的总数。
using System;
using System.Xml;

namespace ReadingXML2{
      class Class1{
            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;

                  // Read a document
                  XmlTextReader textReader   = new XmlTextReader("C://books.xml"); 

                  // Read until end of file
                  while (textReader.Read()){
                        XmlNodeType nType = textReader.NodeType;

                        // If node type us a declaration
                        if (nType == XmlNodeType.XmlDeclaration){
                              Console.WriteLine("Declaration:" + textReader.Name.ToString());
                              xd = xd + 1;
                                      

                        // if node type is a comment
                        if( nType == XmlNodeType.Comment){
                              Console.WriteLine("Comment:" + textReader.Name.ToString());
                              cc = cc + 1;
                                      

                        // if node type us an attribute
                        if( nType == XmlNodeType.Attribute){
                              Console.WriteLine("Attribute:" + textReader.Name.ToString());
                              ac = ac + 1;
                        }

                        // if node type is an element
                        if ( nType == XmlNodeType.Element){
                              Console.WriteLine("Element:" + textReader.Name.ToString());
                              el = el + 1;
                        }

                        // if node type is an entity/
                        if ( nType == XmlNodeType.Entity ){
                              Console.WriteLine("Entity:" + textReader.Name.ToString());
                              et = et + 1;
                                      

                        // if node type is a Process Instruction
                        if( nType == XmlNodeType.Entity ){
                              Console.WriteLine("Entity:" + textReader.Name.ToString());

                              pi = pi + 1;
                                

                        // if node type a document
                        if( nType == XmlNodeType.DocumentType){
                              Console.WriteLine("Document:" + textReader.Name.ToString());
                              dc = dc + 1;
                        }

                        // if node type is white space
                        if ( nType == XmlNodeType.Whitespace ) {
                              Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());
                              ws = ws + 1;
                        }
                  }

                  // Write the summary
                  Console.WriteLine("Total Comments:" + cc.ToString());
                  Console.WriteLine("Total Attributes:" + ac.ToString());
                  Console.WriteLine("Total Elements:" + el.ToString());
                  Console.WriteLine("Total Entity:" + et.ToString());
                  Console.WriteLine("Total Process Instructions:" + pi.ToString());
                  Console.WriteLine("Total Declaration:" + xd.ToString());
                  Console.WriteLine("Total DocumentType:" + dc.ToString());
                  Console.WriteLine("Total WhiteSpaces:" + ws.ToString());
            }
      }
}

【写XML文件】
XmlWriter类包含些XML文档的方法。这是经常使用的XmlTextWriter 和 XmlNodeWriter类的一个抽象基类。它包含写XML文档的方法和属性。这个类中有许多Writexxx方法来写XML文档的各种类型的项目。例如,WriteNode,WriteString, WriteAttributes, WriteStartElement, 和 WriteEndElement。这些方法被利用来成对的开始和结束。例如,写元素,需要调用WriteStartElement然后写一个字符串接下来是WriteEndElement。
除了许多方法,这个类有3个属性。WriteState, XmlLang, 和 XmlSpace。WriteState用于获得或设置XmlWriter类的状态。
虽然这里不可能表述所有的Writexxx方法,演示其中的一些。
第一件事是通过构造方法创建一个XmlTextWriter的实例。XmlTextWriter有三个重载的构造方法,具有string,stream或TextWriter 作为参数。可以传递一个string(文件名)作为参数来创建实例。在示例中,在C://文件夹下创建一个myXmlFile.xml文件。

// Create a new file in C:// dir
XmlTextWriter textWriter = New XmlTextWriter("C://myXmFile.xml", null) ;

创建实例后,第一件事调用WriterStartDocument方法。当完成文档编辑后调用WriteEndDocument方法和Close方法。
textWriter.WriteStartDocument();
.........
textWriter.WriteEndDocument();
textWriter.Close();

WriteStartDocument 和 WriteEndDocument方法用于开始写文档和关闭文档。在写文档前必须打开文档。WriteComment方法为文档添加注释。它仅仅有一个string类型的参数。WriteString方法是在文档中写入一个字符串。在WriteString, WriteStartElement 和 WriteEndElement方法的帮助下可以将元素写到文档中。WriteStartAttribute 和 WriteEndAttribute将特性写入文档中。
WriteNode是一个常用的写方法,写一个XmlReader到作为文档的节点。例如,可以使用WriteProcessingInstruction 和 WriteDocType方法写一个ProcessingInstruction 和 DocType 项到文档。

//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'softcover'>");

下面示例概况了这些方法并创建新的xml文档具有一些项例如元素,属性,字符串,注释等。参看5-14列。在示例中,创建一个新的xml文件“c:/xmlWriterText.xml”。在示例中使用XmlTextWriter创建新xml文件“c:/xmlWriterTest.xml”。

接下来使用Writexxx方法将注释和元素添加到文档中。使用XmlTextReader读出books.xml文档中元素并使用XmlTextWriter写入到xmlWriterTest.xml文件中。

【示例3】在这个例子中,使用XmlTextWriter 创建一个新文件“myxmlFile.xml”使用它的各种写方法写XML项。
using System;
using System.Xml;  

namespace ReadingXML2{
      class Class1{
            static void Main(string[] args){
                  // Create a new file in C:// dir
                  XmlTextWriter textWriter = new XmlTextWriter("C://myXmFile.xml", null);
                   // Opens the document
                  textWriter.WriteStartDocument();

                  // Write comments
                  textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
                  textWriter.WriteComment("myXmlFile.xml in root dir");

                  // Write first element
                  textWriter.WriteStartElement("Student");
                  textWriter.WriteStartElement("r", "RECORD", "urn:record");

                  // Write next element
                  textWriter.WriteStartElement("Name", "");
                  textWriter.WriteString("Student");
                  textWriter.WriteEndElement();

                  // Write one more element
                  textWriter.WriteStartElement("Address", "");
                  textWriter.WriteString("Colony");
                  textWriter.WriteEndElement();

                   // WriteChars

                  char [] ch = new char[3];
                  ch[0] = 'a';
                  ch[1] = 'r';
                  ch[2] = 'c';                

                  textWriter.WriteStartElement("Char");
                  textWriter.WriteChars(ch, 0, ch.Length);
                  textWriter.WriteEndElement();

                  // Ends the document.
                  textWriter.WriteEndDocument();

                  // close writer
                  textWriter.Close();
            }
      }
}

【使用XmlDocument】XmlDocument类用于表述XML文档。这个类提供了前面讨论的相似的方法和属性。

这个类中两个常用方法Load 和 LoadXml。Load方法从string, stream, TextReader 或 XmlReader中加载XML数据。LoadXml方法从特殊的字符串中加载XML文档。另一个有用的方法是Save。用Save可以写XML数据到string, stream, TextWriter 或 XmlWriter中。

  【示例4】这个代码片段比较容易理解。调用XmlDocument的LoadXml方法加载XML部分并使用Save方法将部分保存成XML文件。
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy Lex</Name></Student>"));

//Save the document to a file.
doc.Save("C://std.xml");

如果使用Console.Out作为参数可以使用Save方法在控制台显示信息。例如:
doc.Save(Console.Out); 

【从数据库中写数据到XML文档】
使用XML和ADO.NET模式,读入数据库中的信息并写入到XML文档中反过来也一样。在这部分,将了解如何读数据库中数据表信息写入到XML文档中。
DataSet类提供了读取关系型数据库数据表的方法和将这个表中信息写入到XML文件的方法,可以使用WriteXml方法写一个dataset表的信息到XML文件。
在这个例子中,使用来自Office 2000或最新版本中的Northwind数据量,也可以使用其他数据库。有一件事情必须做就是连接字符和查询的sql语句。

【示例6】在这个例子中,将创建一个数据适配器对象并查询Customers表中的所有记录。后使用Fill方法将从数据适配器中填充到dataset中。

在这个例子中,使用OldDd数据提供程序。在程序中要使用OldDb数据适配器需要引入Syste.Data.OldDb命名空间。正如这个示例中一样,要先创建一个链接到northwind数据的OldDbConnection。后创建一个数据适配器对象将查询sql语句和链接作为参数。一但有了数据适配器,可以使用Fill方法将数据适配器填充到dataset中。然后,可以使用DataSet的WriteXml方法创建一个XML文档并将内容写入到XML文档中。在下面例子中,读入Custmoers表中的记录并写入到DataSet内容到C:/下的OutputXml.Xml文件中。

using System;
using System.Xml;
using System.Data;
using System.Data.OleDb;

namespace ReadingXML2{
      class Class1{
            static void Main(string[] args){

                  // create a connection
                  OleDbConnection con = new OleDbConnection();
                  con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C://Northwind.mdb";                

                  // create a data adapter
                  OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);
                  // create a new dataset
                  DataSet ds = new DataSet();                

                  // fill dataset
                  da.Fill(ds, "Customers");
                  // write dataset contents to an xml file by calling WriteXml method
                  ds.WriteXml("C://OutputXML.xml");                            

            }
      }
}

【概述】
.NET框架类库提供了好的支持对XML文档的处理。XmlReader, XmlWriter和他们的继承类包含了读写文档的方法和属性。通过XmlDocument 和 XmlDataDocument可以读整个文档。XmlDocument的Load和Save方法可以加载一个阅读器或一个文件并分别保存文档。ADO.NET提供了读数据库的方法并可以使用数据适配器和DataSet对象将内容写入到XML文档中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜晚回家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值