ASP.NET 2.0 XML 系列(5):用XmlReader读取XML文档

news/2024/7/6 0:46:05

一、使用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 ="width: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.niftyadmin.cn/n/3040894.html

相关文章

mysql xml配置c_mysql主存配置

主要的事情写在前面: 主从配置文件主配置里面有一条 binlog-do-db&#xff1a;是指定mysql的binlog日志记录哪个数据库(库的名字)从配置里面有一条 eplicate-do-db:这个参数是在slave上配置&#xff0c;指定slave要复制哪个库所以上面两个一定要写上,才会成功.MySQL主从同步1. …

lighttpd配置实例

lighttpd异常自动重启脚本 1.建立脚本 vi /root/bin/check_lighttpd.sh #!/bin/bash datedate %Y-%m-%d-%H-%M if curl –head http://www.gaojinbo.com/index.html | grep "200" >/dev/null 2>&1 ; then echo lighttpd is ok $date >>/root/bin/c…

google proto buffer实战

使用与Thrift类似—— 下载EXE https://developers.google.com/protocol-buffers/docs/downloads Demo地址 https://developers.google.com/protocol-buffers/docs/javatutorial#compiling-your-protocol-buffers 中有addressbook.proto内容 举例子&#xff1a;放在 D:\Users\g…

sniper的中文翻译的pdf版本 BSD ROOTKIT 设计

sniper的中文翻译的pdf版本http://www.zif.cn/bsdrootkit.pdf转载于:https://blog.51cto.com/axlrose/1292982

PostgreSQL 10 build-in table partition(Range)

1.下载 rpm知识库包操作系统版本&#xff1a;CentOS Linux release 7.2.1511 (Core) X64[rootlocalhost home]# yum install https://download.postgresql.org/pub/repos/yum/testing/10/redhat/rhel-7-x86_64/pgdg-centos10-10-1.noarch.rpm Preparing... …

一次Mysql故障诊断过程

一次Mysql故障诊断过程<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />作者&#xff1a;田逸([email]sery163.com[/email]) from: [url]http://netsecurity.51cto.com/art/200803/67632.htm[/url]那天因参加MS的新品发布大会&a…

protocol buffer开发文档

欢迎来到protocol buffer开发文档。protocol buffers是一个语言无关、平台无关、序列化结构数据可扩展的用来协议交互、数据存储等的解决方案。本文档的目标受众是那些想要在他们的应用中使用protocol buffer的Java&#xff0c;C或者Python开发者。这个总览将介绍protocol buff…

如何删除写保护的文件_Windows小知识:如何删除“不能”删除的文件?

我们来看看如何删除那些“不能”删除的文件&#xff0c;比如&#xff1a;FlashHelperServiceZhuDongFangYu(这个别乱搞&#xff0c;删了360可能会出问题&#xff1f;)其实&#xff0c;“不能”删除只是看起来不能删而已&#xff0c;并不表示真的就删除不了。不能删除的原因分析…