如何显示从 xml 文件到 wpf treeview 的文件夹结构?我已经尝试过 Josh Smith 文章http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewModel的第二部分(区域),但是,如何扫描或显示 xml包含未知级别数的文件夹结构的文件?
下面是我想在 wpf treeview 中显示的 xml 文件。将名称作为属性而不是元素是更好的做法吗?
<?xml version="1.0" encoding="utf-8"?>
<Folder>
<Folders />
<FolderName>
<dir>
<name>RootDir</name>
<file>
<name>dobatchfile.bat</name>
</file>
<dir>
<name>Build</name>
<dir>
<name>BuildProcessTemplates</name>
<file>
<name>AzureContinuousDeployment.11.xaml</name>
</file>
<file>
<name>DefaultTemplate.11.1.xaml</name>
</file>
</dir>
</dir>
</dir>
</FolderName>
</Folder>
PS 下面是我不成功的尝试。我正在尝试将 xml 文件内容保存到列表中,以使用 mvvm 模式绑定到我的 wpf 树视图。
public static List<Directory> GetRegions()
{
List<Directory> ret = new List<Directory>();
//var expandolist = GetExpandoFromXml("C:\\New folder/Region1.xml", "Regions", "");
var expandolist = GetExpandoFromXmlRoot("c:\\temp/SerializationOverview.xml", "Regions", "");
expandolist.ToList().ForEach(element =>
{
var dictionary = element as IDictionary<string, object>;
// dictionary.ToList().ForEach(d => ret.Add(new Directory(d.Key)));
dictionary.Where(d => d.Key == "name" || d.Key == "dir").ToList().ForEach(d => ret.Add(new Directory(d.Value.ToString())));
});
return ret;
}
public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid, string Selection)
{
var expandoFromXml = new List<dynamic>();
var doc = XDocument.Load(file);
//foreach (var element in doc.Root.Descendants(descendantid))
foreach (var element in doc.Root.Descendants())
{
dynamic expandoObject = new ExpandoObject();
var dictionary = expandoObject as IDictionary<string, object>;
foreach (var child in element.Elements().Where(e => e.Parent.Parent.Value.Contains(Selection)))
//foreach (var child in element.Descendants())
{
if (child.Name.Namespace == "")
dictionary[child.Name.ToString()] = child.Value.Trim();
// dictionary[child.Name.ToString()] = child.Attributes().FirstOrDefault().Value;
}
yield return expandoObject;
}
}