c#遞歸生成XML實例。本站提示廣大學習愛好者:(c#遞歸生成XML實例)文章只能為提供參考,不一定能成為您想要的結果。以下是c#遞歸生成XML實例正文
本文實例講述了c#遞歸生成XML的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
這裡聯合網上搜到的材料,寫了個遞歸生成xml,經由調試可使用,數據庫構造以下圖所示:
代碼以下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
//using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class frmReadXML : Form
{
public frmReadXML()
{
InitializeComponent();
}
public string connstr = System.Configuration.ConfigurationManager.AppSettings["connstr"].ToString();
private void frmReadXML_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "select * from Nationals";
comm.Connection = conn;
comm.CommandType = CommandType.Text;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = comm;
DataSet ds = new DataSet();
sda.Fill(ds);
XmlDocument doc = new XmlDocument();
doc.AppendChild(doc.CreateXmlDeclaration("1.0","",""));
XmlElement rootnode = doc.CreateElement("root");
doc.AppendChild(rootnode);
CreateXMLtree(ds,doc,"",(XmlElement)null);
}
DataRow[] dr;
public void CreateXMLtree(DataSet ds, XmlDocument doc, string parentCode,XmlElement parentNode)
{
if (parentCode == "")
{
dr = ds.Tables[0].Select("parentCode=''");
}
else
{
dr = ds.Tables[0].Select("parentCode='" + Convert.ToString(parentCode) + "'");
}
XmlElement tempNode;
foreach (DataRow drv in dr)
{
if (parentCode == "")
{
tempNode = doc.CreateElement("c"+drv["Code"].ToString()); //創立一級節點
tempNode.SetAttribute("name", drv["name"].ToString()); //創立屬性
//tempNode.InnerText = drv["name"].ToString();
doc.DocumentElement.AppendChild(tempNode);//添加一級節點
CreateXMLtree(ds,doc,drv["Code"].ToString(),tempNode);
}
else
{
tempNode = doc.CreateElement("c"+drv["Code"].ToString().WordStr(".", ""));
tempNode.SetAttribute("name", drv["name"].ToString());
//tempNode.InnerText = drv["name"].ToString();
parentNode.AppendChild(tempNode);
CreateXMLtree(ds, doc, drv["Code"].ToString(), tempNode);
}
}
doc.Save(AppDomain.CurrentDomain.BaseDirectory+"/xxx.xml");
}
}
}
願望本文所述對年夜家的C#法式設計有所贊助。