c#递归生成XML实例
本文实例讲述了c#递归生成xml的方法。分享给大家供大家参考。具体实现方法如下:
这里结合网上搜到的资料,写了个递归生成xml,经过调试可以使用,数据库结构如下图所示:
代码如下:
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().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#程序设计有所帮助。