基于具有“ID”和“父ID”的元素序列重构XML树

我想要发生的是我想要将ID等于ParentID的元素放入其中? 所以在我的例子中,ParentId = 1的组应该在Id = 1的组中,我怎么能这样做? 好困惑..

在此处输入图像描述

截至目前,这是我的代码:

XElement xroot = new XElement("Root"); XElement xnavigations = null; XElement xmenus = null; foreach (DataRow navigations in GetNavigationSets().Rows) { xnavigations = new XElement("Group", new XElement("GroupName", navigations["name"].ToString()) ); xnavigations.SetAttributeValue("Id", navigations["id"].ToString()); xnavigations.SetAttributeValue("ParentId", navigations["parent_id"].ToString()); foreach (DataRow menus in GetMenusInNavigationSetByNavigation(int.Parse(navigations["id"].ToString())).Rows) { foreach (DataRow menu in GetMenuById(int.Parse(menus["menu_id"].ToString())).Rows) { xmenus = new XElement("Menu", new XElement("Name", menu["name"].ToString()), new XElement("Price", menu["price"].ToString()), new XElement("Description", menu["description"].ToString()) ); xnavigations.Add(xmenus); } } xroot.Add(xnavigations); } xroot.Save("main.xml"); 

新产出:

在此处输入图像描述

这是一种变异方法,它依赖于副作用 。 它不像递归和重建一样干净,但它通常“足够”。 而且,编写起来非常简单。

输入“XML”:

 var root = XElement.Parse(@"      "); 

变成树:

 // So we can find parent by ID var groupMap = root.Elements("group") .ToDictionary(e => (string)e.Attribute("id"), e => e); // ToList so we don't iterate modified collection foreach (var e in root.Elements().ToList()) { XElement parent; if (groupMap.TryGetValue((string)e.Attribute("parent") ?? "", out parent)) { // Unlike standard XML DOM, // make sure to remove XElement from parent first e.Remove(); // Add to correct parent parent.Add(e); } } // LINQPad :-) // root.Dump(); 

输出XML: