本帖最后由 vvvwwvvv 于 2012-05-03 17:36:05 编辑

解决方案 »

  1.   

    http://www.cnblogs.com/yknb/archive/2009/03/06/1404986.html
      

  2.   

    多加了个根元素Item,防止多个PID=0会出现多个根元素    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; }
            }
        }<?xml version="1.0" encoding="utf-8"?>
    <Item>
      <Item ID="1" PID="0" Name="1">
        <Item ID="2" PID="0" Name="1.1">
          <Item ID="3" PID="0" Name="2.1">
            <Item ID="5" PID="0" Name="2.1.1" />
          </Item>
          <Item ID="4" PID="0" Name="2.2">
            <Item ID="6" PID="0" Name="2.2.1" />
          </Item>
        </Item>
      </Item>
    </Item>
      

  3.   


    这个很有效,而且我也成功改为 dataset to treeview了
    但是还是搞不明白~~~
    IEnumerable<ListItem> ie = list.Where(x => x.PID == PID);
    这个的作用是选择指定PID的项???和CreateNode(list, item.ID, xml, element);
    这个是重复调用自己,但是当ID=5的时候就没有子项了他怎么还会找到ID=6的项???
      

  4.   

    IEnumerable<ListItem> ie = list.Where(x => x.PID == PID);这个的作用是选择指定PID的项???是的
    ===================
    CreateNode(list, item.ID, xml, element);这个是重复调用自己,但是当ID=5的时候就没有子项了他怎么还会找到ID=6的项???递归调用。
    当ID=5的时候
    选择ID=5的时候,没有子项,所以上面的xml中Item id=5没有子节点
    当ID=4的时候,会选择PID=4也就是ID=6,把6的element添加到4的节点中。