zoukankan      html  css  js  c++  java
  • ASP.NET 2.0 XML 系列(5):用XmlReader读取XML文档

    一、使用XmlReader类的步骤如下

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

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

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

    (一)开始读取文档

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

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

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

    (二)读取元素

    Read(), ReadString(),ReadStartElement(),ReadEndElement()都能读取Element节点。每个方法都调到文档的下一个节点。MovetoElement()只移动到下一个节点而不读取它。

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

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

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

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

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

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

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

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

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

    二、实例:

    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.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; background-color:#8ABBDF;  color:White;">
        
    <asp:Label ID="mEmployeesLabel" runat="server" Text=""></asp:Label>
        
    </div>
        
    </form>
    </body>
    </html>

    3.读取元素 代码


            string xmlFilePath=Request.PhysicalApplicationPath+@"\Employees.xml";
                
    try
                
    {
                    
    using (XmlReader reader=XmlReader.Create(xmlFilePath))
                    
    {
                        
    string result;
                        
    while (reader.Read())
                        
    {
                            
    if (reader.NodeType == XmlNodeType.Element)
                            
    {
                                result 
    = "";
                                
    for (int count = 0; count < reader.Depth; count++)
                                
    {
                                    result 
    += "---";
                                }

                                result 
    += "->" + reader.Name + "<br/>";
                                
    this.mEmployeesLabel.Text += result;
                            }

                        }

                    }

                }

                
    catch (Exception ex)
                
    {
                    
    this.mEmployeesLabel.Text = "An Exception occured:" + ex.Message;
                }

    4.效果

    xmlreadersample

    5.读取元素和属性名称代码


    protected void Page_Load(object sender, EventArgs e)
           
    {          
               
    string xmlFilePath=Request.PhysicalApplicationPath+@"\Employees.xml";
               
    try
               
    {
                   
    using (XmlReader reader=XmlReader.Create(xmlFilePath))
                   
    {
                       
    string result;
                       
    while (reader.Read())
                       
    {
                           
    if (reader.NodeType == XmlNodeType.Element)
                           
    {
                               result 
    = "";
                               
    for (int count = 0; count < reader.Depth; count++)
                               
    {
                                   result 
    += "---";
                               }

                               result 
    += "->" + reader.Name ; 
                               
    this.mEmployeesLabel.Text += result;
                               
    //开始读属性
                               if (reader.HasAttributes)
                               
    {
                                   
    this.mEmployeesLabel.Text += "(";
                                   
    for (int count = 0; count < reader.AttributeCount; count++)
                                   
    {
                                       reader.MoveToAttribute(count);
                                       
    this.mEmployeesLabel.Text += reader.Name+",";
                                   }

                                   
    this.mEmployeesLabel.Text += ")";                            
                               }

                               
    this.mEmployeesLabel.Text += "<br/>";
                           }

                       }

                   }

               }

               
    catch (Exception ex)
               
    {
                   
    this.mEmployeesLabel.Text = "An Exception occured:" + ex.Message;
               }

           }


      运行结果:

    ->employees
    ---->employee(id,)
    ------->name
    ---------->firstName
    ---------->lastName
    ------->city
    ------->state
    ------->zipCode
    ---->employee(id,)
    ------->name
    ---------->firstName
    ---------->lastName
    ------->city
    ------->state
    ------->zipCode

    6. 读取内容


    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;
               }

           }

     效果:

    Employees
    • Employee-1
      • ID-1
      • First Name-Jack
      • Last Name-Wang
      • City-BeiJing
      • state-BeiJing
      • state-100061
    • Employee-2
      • ID-2
      • First Name-DeHua
      • Last Name-Liu
      • City-Hongkong
      • state-China
      • state-61

    扫码关注公众号,了解更多管理,见识,育儿等内容

    作者: 王德水
    出处:http://www.cnblogs.com/cnblogsfans
    版权:本文版权归作者所有,转载需经作者同意。

  • 相关阅读:
    哈夫曼树及哈夫曼编码
    01背包问题
    Java IO
    Java对象的复制三种方式
    TCP三次握手和四次挥手
    轻量级Java Web框架的实现原理
    Java并发
    消息队列
    赋值、浅拷贝、深拷贝
    Python文件操作(txtxlsxcsv)及os操作
  • 原文地址:https://www.cnblogs.com/cnblogsfans/p/1107321.html
Copyright © 2011-2022 走看看