Asp.net XML心得2:读xml文档的属性

本文提供了一个使用C#解析XML文件的示例代码,并展示了如何遍历XML节点及其属性。通过对XML文件进行逐行读取,代码能够展示每个元素的名称及属性,适用于初学者了解XML文件的基本结构。

xml:

 

ExpandedBlockStart.gif01.xml
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <Menus>
 3   <Menu title="常用网址">
 4     <item name="天下网" url="http://www.netskycn.com" id="1"/>
 5     <item name="天下网生活论坛" url="http://life.netskycn.com" id="2"/>
 6     <item name="csdn" url="http://www.youkuaiyun.com" id="3"/>
 7     <item name="我的博客" url="http://blog.youkuaiyun.com/zhoufoxcn" id="4"/>
 8     <item name="百度" url="http://www.baidu.com" id="5"/>
 9     <item name="Google" url="http://www.google.cn" id="6"/>
10     <item name="微软" url="http://www.microsoft.com" id="7"/>
11   </Menu>
12   <Menu title="娱乐网址">
13     <item name="奇虎" url="http://www.qihoo.com" id="12"/>
14     <item name="网易" url="http://www.163.com" id="13"/>
15     <item name="天涯" url="http://www.tianya.cn" id="14"/>
16   </Menu>
17   <Menu title="安全网址">
18     <item name="360" url="http://www.safe360.com" id="15"/>
19     <item name="瑞星" url="http://www.rising.com.cn" id="16"/>
20   </Menu>
21 </Menus>

 

 

c#:

 

ExpandedBlockStart.gif代码
 1 protected void Page_Load(object sender, EventArgs e)
 2     {
 3         using(XmlReader dr = XmlReader.Create(Server.MapPath("01.xml")))
 4         {
 5             while(dr.Read())
 6             {
 7                 if (dr.NodeType == XmlNodeType.Element)
 8                 {
 9                     for (int dep = 0; dep < dr.Depth; dep++)
10                     {
11                         Label1.Text += "===";
12                     }
13                     Label1.Text += ("==>" + dr.Name);
14 
15                     if (dr.HasAttributes)
16                     {
17                         Label1.Text += "(";
18                         for (int count = 0; count < dr.AttributeCount; count++)
19                         {
20                             dr.MoveToAttribute(count);
21                             Label1.Text += dr.Name + "  ";
22                         }
23                         Label1.Text += ")";
24                     }
25                 }
26                 Label1.Text += "</br>";
27             }
28         }
29         
30     }

 

 

 

输出结果:

转载于:https://www.cnblogs.com/HelloCG/archive/2010/03/24/1693917.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值