C# 遍历 XML文件 节点 net XML节点 遍历

本文介绍了一种遍历XML文件的方法,通过递归函数实现对XML文件中所有节点的读取与处理,并展示了如何利用C#进行XML数据的加载与解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#region 遍历XML文件 调用方法 调用方法 XmlFileAllNodes(Server.MapPath("treeout.xml"), "")
        
/// <summary>
        
/// 添加栏目的临时级别
        
/// </summary>
        int XmlFileAllNodesCloumnLvTemp = 0;

        
/// <summary>
        
/// 添加栏目的临时ID
        
/// </summary>
        int XmlFileAllNodesColumnsIDTemp = 0;

        
/// <summary>
        
/// 添加栏目函数
        
/// </summary>
        
/// <param name="xmlpath">XML栏目文件</param>
        
/// <param name="XmlData">为空 "" </param>
        
/// <![CDATA[调用方法 XmlFileAllNodes(Server.MapPath("treeout.xml"), "")]]>
        
/// <returns></returns>
        public string XmlFileAllNodes(string xmlpath, String XmlData)
        {
            System.Xml.XmlDataDocument MyXml 
= new System.Xml.XmlDataDocument();
            
if (XmlData == "")
            {
                MyXml.Load(xmlpath);
//得到XML数据
            }
            
else
            {
                MyXml.LoadXml(XmlData);
            }

            
for (int i = 0; i < MyXml.DocumentElement.ChildNodes.Count; i++)
            {

                
try
                {   
//得到树状结构
                    if (XmlFileAllNodesCloumnLvTemp == 0)//一级节点
                    {
                      System.Web.HttpContext.Current.Response.Write(TextData.EStr(XmlFileAllNodesCloumnLvTemp, 
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+ XmlFileAllNodesColumnsIDTemp + MyXml.DocumentElement.ChildNodes[i].Attributes.GetNamedItem("Cont").Value + XmlFileAllNodesCloumnLvTemp + " <br/>");
                    }
                    
else
                    {

                        System.Web.HttpContext.Current.Response.Write(TextData.EStr(XmlFileAllNodesCloumnLvTemp, 
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+ XmlFileAllNodesColumnsIDTemp + MyXml.DocumentElement.ChildNodes[i].Attributes.GetNamedItem("Cont").Value + XmlFileAllNodesCloumnLvTemp + " <br/>");
                        
//如果是子节点

                    }
                    XmlFileAllNodesColumnsIDTemp 
+= 1;
                    XmlFileAllNodesCloumnLvTemp
++;
                    XmlFileAllNodes(xmlpath, MyXml.DocumentElement.ChildNodes[i].OuterXml);
//得到这个XML文件下的所有子节点
                    XmlFileAllNodesCloumnLvTemp--;
                }
                
catch (System.Xml.XmlException)//这里如是最下层就不进行下一次的调用自己了
                {
                }
            }
            
return "";
        }
        
#endregion

 

XML文件

<?xml version="1.0" encoding="utf-8"?>
<AddColumns>
  
<Column Name="添加栏目名称1" Lx="栏目分类"  dir="" pic=" 栏目图片" ItempAdderss="栏目模板地址" itempParam=""   TabName="" Cont=" 'djflksjdlfjl 分 &amp;  1 ==&quot;">
  
</Column>

</AddColumns>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值