最近在做关于公司B2B网站的权限整合,临时整理和网上搜到的一些资料,留着备用

将User的对应权限整合成XML文档

//数据库返回的Datatable

DataTable tb = db.ExecuteDataTable("Select * from 编码表");

//创建xml文档对象

XmlDocument doc = new XmlDocument();

//xml头

doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));

//声明

//根元素

doc.AppendChild(doc.CreateElement("root")); //根节点

//用于存放临时数据的xml元素数组

XmlElement[] menu = new XmlElement[tb.Rows.Count];

for (int i = 0; i < tb.Rows.Count; i++)

{

DataRow r = tb.Rows[i];

//创建一个xml元素并放到文档的根目录下

menu[i] = doc.CreateElement("c" + r["code"].ToString().Replace(".", "")); //元素名:

c+code menu[i].SetAttribute("code", r["code"].ToString());//代码

menu[i].SetAttribute("name", r["name"].ToString()); //名称

menu[i].SetAttribute("parentCode", r["parentCode"].ToString()); //父代码

menu[i].SetAttribute("hierarchy", r["hierarchy"].ToString()); //深度 doc.DocumentElement.AppendChild(menu[i]);

}

//重新排列xml所有节点的位置

for (int i = 0; i < menu.Length; i++)

{

if (menu[i].Attributes["hierarchy"].Value != "1") //深度为一的不需要移动,也就是总目录

{

//移动元素,复制一个到父节点下并删除当前元素

//根据当前元素判断父元素的元素名

string parentNodeName = "c" + menu[i].Attributes["parentCode"].Value;

string xpath = string.Format("//{0}[@code={1}]", parentNodeName, menu[i].Attributes["parentCode"].Value);

doc.DocumentElement.SelectSingleNode(xpath).AppendChild(menu[i].Clone());

menu[i].ParentNode.RemoveChild(menu[i]);

}

}

//现在的xml表现为:

//<?xml version="1.0" encoding="utf-8" ?>

//<root>

//<c01 code="01" name="政治" parentCode="" hierarchy="1">

//<c0101 code="01.01" name="国家概况" parentCode="01" hierarchy="2">

//<c010101 code="01.01.01" name="政治体制" parentCode="01.01" hierarchy="3">

//<c01010102 code="01.01.01.02" name="领导体制" parentCode="01.01.01" hierarchy="4"> </c01010102>

//</c010101>

//</c0101>

//</c01>

//<c02 code="02" name="选举制" parentCode="" hierarchy="1">

//... ....... . . .

//</c02>

//</root>

//你可以自己再把多余的属性删掉

posted @ 2010-10-18 14:26  jake_geeeeee  阅读(132)  评论(0)    收藏  举报