zoukankan      html  css  js  c++  java
  • XML参考 :XmlReader 详解、实例

    XML参考 :XmlReader 详解、实例-- 详解

    转:http://www.cnblogs.com/Dlonghow/archive/2008/07/28/1252191.html

    XML参考 :XmlReader 详解、实例(1)-- 详解

     

    .NET Framework 类库

    XmlReader 类

     

    表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。

    XmlReader 在发生 XML 分析错误时引发 XmlException。引发异常后,读取器的状态不可预知。例如,报告的节点类型可能不同于当前节点的实际节点类型。使用 ReadState 属性可以检查读取器是否处于错误状态。

    一、使用XmlReader类的步骤如下

    (1) 使用XmlReader类的Create()创建该类的一个实例,并将被读取的XML文件名称作为参数传入方法

    (2) 建立一个反复调用的Read()方法的循环。这个方法从文件的第一个节点开始,然后读取所有余下的节点,但每次调用只读取一个节点,如果存在一个节点可被读取 则返回True,当到达文件最后时返回False.

    (3) 在这个循环中将检查XmlReader对象的属性和方法,以获得当前节点的信息(类型、名称、数据等等),不断地执行该循环知道Read()返回False.

    (一)开始读取文档

    要开始读取xml文档,你可以调用任意一个Read()方法,XmlReader XmlTextReaderXmlNodeReaderXmlValidatingReader 如:

    XmlReader reader = XmlReader.Create("Employees.xml");
    reader.ReadStartElement();

    或者reader.MoveToContent()直接跳至文档内容。如果当前节点不是内容节点(内容节点是CDATA, Element,Entity,EntityReference).如果位于属性上,将会返回至包含该属性的元素。

    【重要事项】:

    虽然 Microsoft .NET Framework 包含 XmlReader 类的具体实现,如 XmlTextReaderXmlNodeReaderXmlValidatingReader 类,但是在 2.0 版本中,建议的做法是使用 Create 方法创建 XmlReader 实例。

    (二)读取元素

    (1)Read(), ReadString(),ReadStartElement(),ReadEndElement()都能读取Element节点。

    (2)每个方法都调到文档的下一个节点。

    (3)MovetoElement()只移动到下一个节点而不读取它。

    当XmlReader读取文档时,它的状态有可能如下:

    成员名称说明
    Closed 已调用 Close 方法。
    EndOfFile 已成功到达文件结尾。
    Error 出现错误,阻止读取操作继续进行。
    Initial 未调用 Read 方法。
    Interactive 已调用 Read 方法。可能对读取器调用了其他方法。
     
    (三)读取属性
    应当先用HasAttributes检查是否有属性,然后可以通过MoveToAttribute(), MoveToFirstAttribute(),MoveToNextAttribute()来访问
          XmlReader reader = XmlReader.Create("Employees.xml");
          if (reader.HasAttributes)
          
     

    (四)读取内容和其他数据

    ReadString()读取当前节点内容为字符串,还可以使用ReadElementContentAsXXX(),ReadContentAsXXX可以在当前位置读取文本内容。

    该方法返回元素的内容、文本、空白、重要空白或 CDATA 节点。

    如果定位在元素上,ReadString 将所有文本、重要的空白、空白和 CDATA 节节点串联在一起,然后将串联在一起的数据作为元素内容返回。当遇到任何标记(包括注释和处理指令)时,它就会停止。这可以在混合内容模型中发生,也可以在读取元素结束标记时发生。

    如果定位在元素文本节点上,则 ReadString 执行相同的串联,即从该文本节点到元素结束标记。如果读取器定位在属性文本节点上,则 ReadString 与读取器定位在元素开始标记上时的功能相同。它返回所有串联在一起的元素文本节点。

    如果定位在属性上,则 ReadString 将返回空字符串,并将读取器移回到拥有该属性的元素。

    如果在任何其他节点类型上调用 ReadString,则它将返回空的字符串并将读取器定位在下一个节点上。

    转:http://www.cnblogs.com/Dlonghow/archive/2008/07/28/1254261.html

    XML参考 :XmlReader 详解、实例(2)-- 读取XML节点

     

    .NET Framework 类库

    XmlReader 类

     

    表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。

    二.实例,读取XML节点

    1. 我们先创建一个Employees.xml的文件

    复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <employees>
      <employee id="1">
        <name>
          <firstName>Jack</firstName>
          <lastName>Wang</lastName>
        </name>
        <city>BeiJing</city>
        <state>BeiJing</state>
        <zipCode>100061</zipCode>
      </employee>
      <employee id="2">
        <name>
          <firstName>DeHua</firstName>
          <lastName>Liu</lastName>
        </name>
        <city>Hongkong</city>
        <state>China</state>
        <zipCode>000061</zipCode>
      </employee>
    </employees>
    复制代码

    2.读取元素的代码:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;

    namespace JackDong.XmlReaderDemo
    {
        class XmlReaderDemo
        {
           private static string xmlFilePath = @"....EmployeeInfo.xml";// @"D:\EmployeeInfo.xml"

            public static string ReadXml()
            {
                string result = "";

                try
                {
                    using (XmlReader reader = XmlReader.Create(xmlFilePath))
                    {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                for (int count = 0; count < reader.Depth; count++)
                                {
                                    result += "---";
                                }
                                result += "->" + reader.Name + " ";
                            }
                        }
                    }
                }
                catch (Exception ex){
                    result += "An Exception occured: " + ex.Message; 
                }
                return result;
            }
        }

        class Program
        {
            static void Main()
            {
                string strReturn = XmlReaderDemo.ReadXml();
                Console.WriteLine(strReturn);
                Console.ReadLine();
            }
        }
    }
    复制代码

    3.执行效果如下:

     转:http://www.cnblogs.com/Dlonghow/archive/2008/07/28/1254290.html

    XML参考 :XmlReader 详解、实例(3)-- 读取XML节点和属性名称

     

    .NET Framework 类库

    XmlReader 类

     

    表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。

    三.读取XML节点和属性名称

    复制代码
    class XmlReaderDemo
        {
            private static string xmlFilePath = @"....EmployeeInfo.xml";// @"D:\EmployeeInfo.xml"

            public static string ReadXml()
            {
                string result = "";
                try
                {
                    using (XmlReader reader = XmlReader.Create(xmlFilePath))
                    {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                for (int count = 0; count < reader.Depth; count++)
                                {
                                    result += "";
                                }
                                result += "->" + reader.Name;
                                if (reader.HasAttributes)
                                {
                                    result += "(";
                                    for (int count = 0; count < reader.AttributeCount; count++)
                                    {
                                        reader.MoveToAttribute(count);
                                        result += reader.Name + ",";
                                    }
                                    result += ")";
                                }
                                result += " ";
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    result += "An Exception occured: " + ex.Message;
                }
                return result;
            }
        }

        class Program
        {
            static void Main()
            {
                string strReturn = XmlReaderDemo.ReadXml();
                Console.WriteLine(strReturn);
                Console.ReadLine();
            }
        }
    复制代码

    效果图如下所示:

     
     
     

    XML参考 :XmlReader 详解、实例(4)-- 读取XML内容

     

    .NET Framework 类库

    XmlReader 类

     

    表示提供对 XML 数据进行快速、非缓存、只进访问的读取器,即 对 XML 数据流的只进只读访问。XmlReader 类符合 W3C 可扩展标记语言 (XML) 1.0 和“XML 中的命名空间”建议。

    1.实例:读取XML内容

    page页面代码:

    复制代码
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div style="400px; border:solid 1px #000;    color:White;">
        <asp:Label ID="mEmployeesLabel" runat="server" Text=""></asp:Label>
        </div>
        </form>
    </body>
    </html>
    复制代码

    2.读取XML内容的代码

    复制代码
    protected void Page_Load(object sender, EventArgs e)
           {
               string employeeID = "";
               string xmlFilePath = Request.PhysicalApplicationPath + @"Employees.xml";
               try
               {
                   using (XmlReader reader = XmlReader.Create(xmlFilePath))
                   {
                       this.mEmployeesLabel.Text = "<b>Employees</b>";
                       this.mEmployeesLabel.Text += "<ul>";                   

                       while (reader.Read())
                       {
                           if (reader.NodeType == XmlNodeType.Element)
                           {
                               if (reader.Name == "employee")
                               {
                                    employeeID = reader.GetAttribute("id");
                                }
                               if (reader.Name == "name")
                               {
                                   this.mEmployeesLabel.Text += "<li>" + "Employee-" + employeeID;
                                   this.mEmployeesLabel.Text += "<ul>";
                                   this.mEmployeesLabel.Text += "<li>ID-" + employeeID + "</li>";
                                }
                               if (reader.Name == "firstName")
                               {
                                   this.mEmployeesLabel.Text += "<li>First Name-" + reader.ReadString() + "</li>";
                                }
                               if (reader.Name == "lastName")
                               {
                                   this.mEmployeesLabel.Text += "<li>Last Name-" + reader.ReadString() + "</li>";
                                }
                               if (reader.Name == "city")
                               {
                                   this.mEmployeesLabel.Text += "<li>City-" + reader.ReadString() + "</li>";
                                }
                               if (reader.Name == "state")
                               {
                                   this.mEmployeesLabel.Text += "<li>state-" + reader.ReadString() + "</li>";
                                }
                               if (reader.Name == "zipCode")
                               {
                                   this.mEmployeesLabel.Text += "<li>state-" + reader.ReadElementContentAsInt() + "</li>";
                                }
                            }
                           else if (reader.NodeType == XmlNodeType.EndElement)
                           {
                               if (reader.Name == "employee")
                               {
                                   this.mEmployeesLabel.Text += "</ul>";
                                   this.mEmployeesLabel.Text += "</li>";
                                }
                            }
                        }
                       this.mEmployeesLabel.Text += "</ul>";
                    }
                }
               catch (Exception ex)
               {
                   this.mEmployeesLabel.Text = "An Exception occured:" + ex.Message;
                }
            }
    复制代码

    3.效果如下:

  • 相关阅读:
    让网页活起来!韵律线带你提升带你飞!
    打造晶格化背景
    简单banner制作
    设计模式-适配器模式
    类、方法的单一职责
    .NET趋势
    C# Delegate Event
    VB.NET项目技术总结
    版本控制工具Git的使用
    delete语句要注意的BUG.
  • 原文地址:https://www.cnblogs.com/flylong0204/p/3927458.html
Copyright © 2011-2022 走看看