递归及如何用c#递归生成多层次XML文件

递归

递归做为一种算法在程序设计语言中广泛应用.是指函数/过程/子程序在运行过程中直接或间接调用自身而产生的重入现象.递归是计算机科学的一个重要概念,递归的方法是程序设计中有效的方法,采用递归编写程序能使程序变得简洁和清晰.。

一般定义
程序调用自身的编程技巧称为递归( recursion)。
一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
注意:
(1) 递归就是在过程或函数里调用自身;
(2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。

递归应用

递归算法一般用于解决三类问题:
(1)数据的定义是按递归定义的。(Fibonacci函数)
(2)问题解法按递归算法实现。(回溯)
(3)数据的结构形式是按递归定义的。(树的遍历,图的搜索)
递归的缺点:
递归算法解题的运行效率较低。在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。
递归次数过多容易造成栈溢出等。


protected void Button1_Click(object sender, EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from [table]", ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString);
        DataTable dt = new DataTable("tab1");
        da.Fill(dt);
        XmlDocument xd = new XmlDocument();
        XmlDeclaration xdl = xd.CreateXmlDeclaration("1.0", "utf-8", null);
        xd.AppendChild(xdl);
        XmlElement xe = xd.CreateElement("root");
        xe = XmlElementCreate(dt,"",xd,xe);
        xd.AppendChild(xe);
        try
        {
            xd.Save("D://XMLCerate.xml");
            Response.Write("OK");
        }
        catch (Exception ee)
        { 
            Response.Write(ee.Message);
        }
    }

    private XmlElement XmlElementCreate(DataTable dt, string parentcode, XmlDocument xd, XmlElement xee)
    {
        string strparentcode="";
        if (parentcode.Trim().Length == 0)
            strparentcode = "parentcode is null";
        else
            strparentcode = "parentcode='" + parentcode + "'";
        DataRow[] dr = dt.Select(strparentcode);
        for (int i = 0; i < dr.Length; i++)
        {
            XmlElement xe = xd.CreateElement("c" + dr[i]["code"].ToString().Replace(".", ""));
            XmlAttribute xaCode = xd.CreateAttribute("code");
            xaCode.Value = dr[i]["code"].ToString();
            xe.Attributes.Append(xaCode);
            XmlAttribute xaName = xd.CreateAttribute("name");
            xaName.Value = dr[i]["name"].ToString();
            xe.Attributes.Append(xaName);
            xe = XmlElementCreate(dt, dr[i]["code"].ToString(), xd, xe);
            xee.AppendChild(xe);
        }
        return xee;
    }

猜你喜欢

转载自blog.csdn.net/dupeng0811/article/details/6318807
今日推荐