日期:2014-05-18 浏览次数:20768 次
class ListItem { public int ID { get; set; } public int PID { get; set; } public string Name { get; set; } }
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" });
<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>
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; } } }