首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

!平面数据表如何生成xml树?

2012-05-04 
求助!平面数据表怎么生成xml树??上网查了很多没看明白,希望有人针对我的代码给个完整例子,谢谢就是要按照

求助!平面数据表怎么生成xml树??
上网查了很多没看明白,希望有人针对我的代码给个完整例子,谢谢
就是要按照数据表无限级的生成xml

C# code
class ListItem    {        public int ID { get; set; }        public int PID { get; set; }        public string Name { get; set; }    }

C# code
     List<ListItem> Lists = new List<ListItem>();     Lists.Add(new ListItem() { ID = 1, PID = 0, Name = "1" });     Lists.Add(new ListItem() { ID = 2, PID = 1, Name = "1.1" });     Lists.Add(new ListItem() { ID = 3, PID = 2, Name = "2.1" });     Lists.Add(new ListItem() { ID = 4, PID = 2, Name = "2.2" });     Lists.Add(new ListItem() { ID = 5, PID = 3, Name = "2.1.1" });     Lists.Add(new ListItem() { ID = 6, PID = 4, Name = "2.2.1" });

生成XML效果
XML code
<Item ID="1" PID="0" Name="1">  <Item ID="2" PID="1" Name="1.1">    <Item ID="3" PID="2" Name="2.1">      <Item ID="5" PID="3" Name="2.11" />    </Item>    <Item ID="4" PID="2" Name="2.2">      <Item ID="6" PID="4" Name="2.2.1" />    </Item>  </Item></Item>


[解决办法]
多加了个根元素Item,防止多个PID=0会出现多个根元素
C# code
    class Program    {        static void Main(string[] args)        {            List<ListItem> Lists = new List<ListItem>();            Lists.Add(new ListItem() { ID = 1, PID = 0, Name = "1" });            Lists.Add(new ListItem() { ID = 2, PID = 1, Name = "1.1" });            Lists.Add(new ListItem() { ID = 3, PID = 2, Name = "2.1" });            Lists.Add(new ListItem() { ID = 4, PID = 2, Name = "2.2" });            Lists.Add(new ListItem() { ID = 5, PID = 3, Name = "2.1.1" });            Lists.Add(new ListItem() { ID = 6, PID = 4, Name = "2.2.1" });            XmlDocument xml = new XmlDocument();            XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "utf-8", null);            XmlNode root = xml.CreateElement("Item");            xml.AppendChild(dec);            xml.AppendChild(root);            CreateNode(Lists, 0, xml, root);            xml.Save(@"E:\a.xml");            Console.ReadLine();        }        public static void CreateNode(List<ListItem> list, int PID, XmlDocument xml, XmlNode node)        {            IEnumerable<ListItem> ie = list.Where(x => x.PID == PID);            foreach (ListItem item in ie)            {                XmlElement element = xml.CreateElement("Item");                element.SetAttribute("ID", item.ID.ToString());                element.SetAttribute("PID", "0");                element.SetAttribute("Name", item.Name);                node.AppendChild(element);                CreateNode(list, item.ID, xml, element);            }        }        public class ListItem        {            public int ID { get; set; }            public int PID { get; set; }            public string Name { get; set; }        }    } 

热点排行