遞迴及如何用c#遞迴生成多層次XML檔案
阿新 • • 發佈:2018-12-25
遞迴
遞迴做為一種演算法在程式設計語言中廣泛應用.是指函式/過程/子程式在執行過程中直接或間接呼叫自身而產生的重入現象.遞迴是電腦科學的一個重要概念,遞迴的方法是程式設計中有效的方法,採用遞迴編寫程式能使程式變得簡潔和清晰.。
一般定義
程式呼叫自身的程式設計技巧稱為遞迴( 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;
}