Last active
August 29, 2015 14:12
-
-
Save mmowbray/dd7155c89e62571a38ea to your computer and use it in GitHub Desktop.
Convert a list of paths into its corresponding hierarchical tree (in XML). Can be used for webpages.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This method accepts a list of strings, where each string is a path (eg. "home/user/max/pic.png") | |
// and creates a hierarchical XML tree out of them | |
using System.Collections.Generic; | |
using System.Xml.Linq; | |
using System.Linq; | |
public string GetTreeViewXml(List<string> paths) | |
{ | |
XDocument doc = new XDocument(new XElement("ul")); | |
XElement currentNode, nextNode; | |
foreach (string path in paths) | |
{ | |
string[] asArray = path.Split('/'); | |
int depth = asArray.Length; | |
currentNode = doc.Root; | |
for (int i = 0; i < depth; i++) | |
{ | |
string directory = asArray[i]; | |
nextNode = (from elem in currentNode.Elements("li") where elem.Nodes().OfType<XText>().First().Value == directory select elem.Element("ul")).FirstOrDefault(); | |
/* this foreach does the same thing as previous line | |
foreach (var elem in currentNode.Elements("li")) | |
{ | |
if (elem.Nodes().OfType<XText>().First().Value == directory) | |
{ | |
nextNode = elem.Element("ul"); | |
break; | |
} | |
} */ | |
if (nextNode == null) | |
{ | |
var newChild = new XElement("li", directory); | |
currentNode.Add(newChild); | |
if (i == depth - 1) | |
break; | |
newChild.Add(new XElement("ul")); | |
nextNode = newChild.Element(("ul")); | |
} | |
currentNode = nextNode; | |
} | |
} | |
return doc.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment