• c# xml的读写


    一.前言: XML是微软.Net战略的一个重要组成部分,而且它可谓是XML Web服务的基石,所以掌握.Net框架下的XML技术自然显得非常重要了。本文将指导大家如何运用C#语言完成.Net框架下的XML文档的读写操作。首先,我会向大家介绍.Net框架中与XML相关的命名空间和其中的重要类。其次,我还会给出有关的实例以使读者更进一步的了解XML文档的读写操作的具体方法。

    二.XML命名空间和相关类简介:

    在深入进行.Net框架下的XML文档的操作之前,我想很有必要向大家介绍.Net框架中与XML技术有关的命名空间和其中一些重要的类。.Net框架为我们提供了以下一些命名空间:System.Xml、System.Xml.Schema、 System.Xml.Serialization、System.Xml.Xpath以及 System.Xml.Xsl来包容和XML操作相关的类。

    System.Xml命名空间包含了一些最重要的XML类,其中最主要的类是和XML文档的读写操作相关的类。这些类中包括4个与读相关的类以及2个与写相关的类。它们分别是:XmlReader、XmlTextReader、 XmlValidatingReader、XmlNodeReader、XmlWriter以及 XmlTextWriter。本文将重点介绍这些类,因为它们是最基本也是最重要的类。

    XmlReader类是一个虚基类,它包含了读XML文档的方法和属性。该类中的Read方法是一个基本的读XML文档的方法,它以流形式读取XML文档中的节点(Node)。另外,该类还提供了ReadString、ReadInnerXml、 ReadOuterXml和ReadStartElement等更高级的读方法。除了提供读XML文档的方法外,XmlReader类还为程序员提供了 MoveToAttribute、MoveToFirstAttribute、MoveToContent、MoveToFirstContent、 MoveToElement以及 MoveToNextAttribute等具有导航功能的方法。在本文后面介绍的实例中,我们将运用到这些方法。

    XmlTextReader、XmlNodeReader以及XmlValidatingReader等类是从XmlReader类继承过来的子类。根据它们的名称,我们可以知道其作用分别是读取文本内容、读取节点和读取XML模式(Schemas)。

    XmlWriter类为程序员提供了许多写XML文档的方法,它是XmlTextWriter类的基类,我在后面的实例中会给出相关的运用方法。

    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中的数据集对象之间的互操作。

    除了上面介绍的System.Xml命名空间中的类外,该命名空间还包括了XmlConvert、XmlLinkedNode以及XmlNodeList等类,不过这些类不是本文介绍的重点,有兴趣的读者不妨去参考相关文档资料。

    System.Xml.Schema命名空间中包含了和XML模式相关的类,这些类包括XmlSchema、XmlSchemaAll、XmlSchemaXPath以及XmlSchemaType等类。

    System.Xml.Serialization命名空间中包含了和XML文档的序列化和反序列化操作相关的类,XML文档的序列化操作能将XML格式的数据转化为流格式的数据并能在网络中传输,而反序列化则完成相反的操作,即将流格式的数据还原成XML格式的数据。

    System.Xml.XPath命名空间包含了XPathDocument、 XPathExression、XPathNavigator以及XPathNodeIterator等类,这些类能完成XML文档的导航功能。在 XPathDocument类的协助下,XPathNavigator类能完成快速的XML文档导航功能,该类为程序员提供了许多Move方法以完成导航功能。

    System.Xml.Xsl命名空间中的类完成了XSLT的转换功能。

    三.读XML文档的方法:

    在介绍完.Net框架中和XML有关的命名空间和相关类后,我接着向大家介绍和XML相关的一些操作。首先,我向大家介绍的读取XML文档的方法。在下面的实例程序中,我将运用VS.net开发工具附带的"books.xml"文件来作为示例。你可以在你的机器上搜索到该文件(或请参考附录),或者你也可以运用其他的XML文件。

    首先,我们用XmlTextReader类的对象来读取该XML文档。方法很简单,就是在创建新对象的构造函数中指明XML文件的位置即可。

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

    一旦新对象创建完毕,你就可以调用其Read方法来读取XML文档了。调用Read方法之后,信息被存储起来,你可以通过读取该对象的Name、BaseURI、Depth、LineNumber等属性来获取这些信息。下面我给出一个完整的实例,该实例通过简单的读取"books.xml"文件,然后将其中的信息显示在控制台中。

    using System; using System.Xml;

    namespace ReadXml { class Class1 { static void Main( string[] args ) { // 创建一个XmlTextReader类的对象并调用Read方法来读取文件 XmlTextReader textReader = new XmlTextReader("C://books.xml"); textReader.Read(); // 节点非空则执行循环体 while ( textReader.Read() ) { // 读取第一个元素 textReader.MoveToElement(); Console.WriteLine("XmlTextReader Properties Test"); Console.WriteLine("===================");

    // 读取该元素的属性并显示在控制台中 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()); } } } }

    XmlTextReader类中有一个很重要的属性-NodeType,通过该属性,我们可以知道其节点的节点类型。而枚举类型XmlNodeType中包含了诸如Attribute、CDATA、Element、Comment、 Document、DocumentType、Entity、ProcessInstruction以及WhiteSpace等的XML项的类型。通过与 XmlNodeType中的元素的比较,我们可以获取相应节点的节点类型并对其完成相关的操作。下面我就给出一个实例,该实例读取每个节点的 NodeType,并根据其节点类型显示其中的内容,同时程序还记录了XML文件中每种节点类型的数目。

    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("C://books.xml");

    while (textReader.Read()) { XmlNodeType nType = textReader.NodeType;

    // 节点类型为XmlDeclaration if (nType == XmlNodeType.XmlDeclaration) { Console.WriteLine("Declaration:" + textReader.Name.ToString()); xd = xd + 1; }

    // 节点类型为Comment if( nType == XmlNodeType.Comment) { Console.WriteLine("Comment:" + textReader.Name.ToString()); cc = cc + 1; }

    // 节点类型为Attribute if( nType == XmlNodeType.Attribute) { Console.WriteLine("Attribute:" + textReader.Name.ToString()); ac = ac + 1; }

    // 节点类型为Element if ( nType == XmlNodeType.Element) { Console.WriteLine("Element:" + textReader.Name.ToString()); el = el + 1; }

    // 节点类型为Entity if ( nType == XmlNodeType.Entity ) { Console.WriteLine("Entity:" + textReader.Name.ToString()); et = et + 1; }

    // 节点类型为Process Instruction if( nType == XmlNodeType.ProcessingInstruction ) { Console.WriteLine("Process Instruction:" + textReader.Name.ToString()); pi = pi + 1; }

    // 节点类型为DocumentType if( nType == XmlNodeType.DocumentType) { Console.WriteLine("DocumentType:" + textReader.Name.ToString()); dc = dc + 1; }

    // 节点类型为Whitespace if ( nType == XmlNodeType.Whitespace ) { Console.WriteLine("WhiteSpace:" + textReader.Name.ToString()); ws = ws + 1; } }

    // 在控制台中显示每种类型的数目 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()); } } }

    以上,我向大家介绍了如何运用XmlTextReader类的对象来读取XML文档,并根据节点的NodeType属性来取得其节点类型信息。同时XmlReader这个基类还有XmlNodeReader和 XmlValidatingReader等派生类,它们分别是用来读取XML文档的节点和模式的。限于篇幅,这里就不介绍了,读者可以参考有关资料。

    四.写XML文档的方法:

    XmlWriter类包含了写XML文档所需的方法和属性,它是XmlTextWriter类和 XmlNodeWriter类的基类。该类包含了WriteNode、WriteString、WriteAttributes、 WriteStartElement以及WriteEndElement等一系列写XML文档的方法,其中有些方法是成对出现的。比如你要写入一个元素,你首先得调用WriteStartElement方法,接着写入实际内容,最后是调用WriteEndElement方法以表示结束。该类还包含了 WriteState、XmlLang和XmlSpace等属性,其中WriteState属性表明了写的状态。因为XmlWriter类包含了很多写 XML文档的方法,所以这里只是介绍最主要的几种。下面我们通过其子类XmlTextWriter类来说明如何写XML文档。

    首先,我们要创建一个XmlTextWriter类的实例对象。该类的构造函数 XmlTextWriter有三种重载形式,其参数分别为一个字符串、一个流对象和一个TextWriter对象。这里我们运用字符串的参数形式,该字符串就指明了所要创建的XML文件的位置,方法如下:

    XmlTextWriter textWriter = New XmlTextWriter("C://myXmFile.xml", null);

    在创建完对象后,我们调用WriterStartDocument方法开始写XML文档,在完成写工作后,就调用WriteEndDocument结束写过程并调用Close方法将它关闭。在写的过程中,我们可以调用WriteComment方法来添加说明,通过调用WriteString方法来添加一个字符串,通过调用WriteStartElement和WriteEndElement方法对来添加一个元素,通过调用WriteStartAttribute和WriteEndAttribute方法对来添加一个属性。我们还可以通过调用 WriteNode方法来添加整一个节点,其它的写的方法还包括WriteProcessingInstruction和WriteDocType等等。下面的实例就是介绍如何具体运用这些方法来完成XML文档的写工作的。

    using System; using System.Xml;

    namespace WriteXML { class Class1 { static void Main( string[] args ) { try { // 创建XmlTextWriter类的实例对象 XmlTextWriter textWriter = new XmlTextWriter("C://w3sky.xml", null); textWriter.Formatting = Formatting.Indented;

    // 开始写过程,调用WriteStartDocument方法 textWriter.WriteStartDocument();

    // 写入说明 textWriter.WriteComment("First Comment XmlTextWriter Sample Example"); textWriter.WriteComment("w3sky.xml in root dir");

    //创建一个节点 textWriter.WriteStartElement("Administrator"); textWriter.WriteElementString("Name", "formble"); textWriter.WriteElementString("site", "w3sky.com"); textWriter.WriteEndElement();

    // 写文档结束,调用WriteEndDocument方法 textWriter.WriteEndDocument();

    // 关闭textWriter textWriter.Close();

    } catch(System.Exception e) { Console.WriteLine(e.ToString()); } } } }

    五.运用XmlDocument类:

    XmlDocument类的对象代表了一个XML文档,它也是一个非常重要的XML类。该类包含了 Load、LoadXml以及Save等重要的方法。其中Load方法可以从一个字符串指定的XML文件或是一个流对象、一个TextReader对象、一个XmlReader对象导入XML数据。LoadXml方法则完成从一个特定的XML文件导入XML数据的功能。它的Save方法则将XML数据保存到一个XML文件中或是一个流对象、一个TextWriter对象、一个XmlWriter对象中。

    下面的程序中我们用到了XmlDocument类对象的LoadXml方法,它从一个XML文档段中读取XML数据并调用其Save方法将数据保存在一个文件中。

    // 创建一个XmlDocument类的对象 XmlDocument doc = new XmlDocument(); doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy Lex</Name></Student>"));

    // 保存到文件中 doc.Save("C://student.xml");

    这里,我们还可以通过改变Save方法中参数,将XML数据显示在控制台中,方法如下:

    doc.Save(Console.Out);

    而在下面的程序中,我们用到了一个XmlTextReader对象,通过它我们读取 "books.xml"文件中的XML数据。然后创建一个XmlDocument对象并载入XmlTextReader对象,这样XML数据就被读到 XmlDocument对象中了。最后,通过该对象的Save方法将XML数据显示在控制台中。

    XmlDocument doc = new XmlDocument(); // 创建一个XmlTextReader对象,读取XML数据 XmlTextReader reader = new XmlTextReader("c://books.xml"); reader.Read();

    // 载入XmlTextReader类的对象 doc.Load(reader); // 将XML数据显示在控制台中 doc.Save(Console.Out);

    六.总结:

    XML技术作为.Net的基石,其重要性自然不言而喻。.Net框架包含了五个命名空间和大量的类来支持与XML技术有关的操作。其中System.Xml是最重要的一个命名空间,其中的XmlReader类和XmlWriter类以及它们的派生类完成了 XML文档的读写操作,是最基本也是最重要的类。XmlDocument类代表了XML文档,它能完成与整个XML文档相关的各类操作,同时和其相关的 XmlDataDocument类也是非常重要的,值得读者的深入研究。

    附录

    "books.xml"文件如下:

    <?xml version='1.0'?> <!-- This file represents a fragment of a book store inventory database --> <bookstore> <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"> <title>The Autobiography of Benjamin Franklin</title> <author> <first-name>Benjamin</first-name> <last-name>Franklin</last-name> </author> <price>8.99</price> </book> <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"> <title>The Confidence Man</title> <author> <first-name>Herman</first-name> <last-name>Melville</last-name> </author> <price>11.99</price> </book> <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6"> <title>The Gorgias</title> <author> <first-name>Sidas</first-name> <last-name>Plato</last-name> </author> <price>9.99</price> </book> </bookstore>

  • 相关阅读:
    C# 不用添加WebService引用,调用WebService方法
    贪心 & 动态规划
    trie树 讲解 (转载)
    poj 2151 Check the difficulty of problems (检查问题的难度)
    poj 2513 Colored Sticks 彩色棒
    poj1442 Black Box 栈和优先队列
    啦啦啦
    poj 1265 Area(pick定理)
    poj 2418 Hardwood Species (trie树)
    poj 1836 Alignment 排队
  • 原文地址:https://www.cnblogs.com/xu3593/p/2806645.html
Copyright © 2020-2023  润新知