日期:2014-05-18  浏览次数:20768 次

求助!平面数据表怎么生成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; }
        }
    }