c#遞歸生成XML實例
本文實例講述了c#遞歸生成XML的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
這里結(jié)合網(wǎng)上搜到的資料,寫了個遞歸生成xml,經(jīng)過調(diào)試可以使用,數(shù)據(jù)庫結(jié)構(gòu)如下圖所示:

代碼如下:
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()); //創(chuàng)建一級節(jié)點
tempNode.SetAttribute("name", drv["name"].ToString()); //創(chuàng)建屬性
//tempNode.InnerText = drv["name"].ToString();
doc.DocumentElement.AppendChild(tempNode);//添加一級節(jié)點
CreateXMLtree(ds,doc,drv["Code"].ToString(),tempNode);
}
else
{
tempNode = doc.CreateElement("c"+drv["Code"].ToString().Replace(".", ""));
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#程序設(shè)計有所幫助。
相關(guān)文章
Unity報錯InvalidOperationException: out of sync的解決
今天在做個東西,發(fā)現(xiàn)報錯,特此來記錄一下,本文介紹了Unity報錯InvalidOperationException: out of sync的解決,感興趣的可以了解一下2021-05-05
C#調(diào)用FFplay實現(xiàn)播放視頻功能
這篇文章主要為大家詳細(xì)介紹了C#如何調(diào)用FFplay實現(xiàn)播放視頻功能,文中的示例代碼講解詳細(xì),具有一定的參考價值,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10

