龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

ASP.NET中用XmlReader读取XML文档教程(2)

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
二、实例: 1. 我们先创建一个Employees.xml的文件 ? xml version="1.0" encoding="utf-8" ? employees employee id ="1" name firstName Jack / firstName lastName Wang / lastName / name city Be

二、实例:

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

 


精彩图集

赞助商链接