我想创建一个目录结构的 XMLDom,如下所示
<ROOT>
<NAME>MainFolder</NAME>
<Path>C:\MainFolder</Path>
<Level1>
<Name>Folder 1</Name>
<Path>C:\MainFolder\Folder 1</Path>
<Level2>
<Name>Folder 1 1</Name>
<Path>C:\MainFolder\Folder 1\Folder 1 1</Path>
</Level2>
<Level2>
<Name>Folder 1 2</Name>
<Path>C:\MainFolder\Folder 1\Folder 1 2</Path>
</Level2>
</Level1>
</ROOT>
如果我试图做的事情会起作用,我不使用,但下面的代码给出了一个错误,说我试图输入非法字符
private static XElement DirToXml(DirectoryInfo dir ,int level)
{
string slevel;
switch (level)
{
case 1:
slevel = "Level1";
break;
case 2:
slevel = "Level2";
break;
case 3:
slevel = "Level3";
break;
default:
slevel = "SoOn";
break;
}
XElement mdoc = XElement.Load("<test></test>");
foreach (var tdir in dir.GetDirectories())
{
XElement doc = XElement.Load("<" + slevel +"> \n <Name>" + dir.Name +"</Name>\n <Path>"+ dir.FullName +"</Path>\n </"+slevel+">");
tdir.GetDirectories().Select(d => DirToXml(d, level++));
mdoc.Add(doc);
}
return mdoc;
//return new XElement("Level1", new XAttribute("Name", dir.Name), dir.GetDirectories().Select(d => DirToXml(d, level ++)));
}
这就是我用来调用 DirToXml 的东西
XDocument xdoc = new XDocument(
new XElement("Root", DirToXml(new DirectoryInfo(@"C:\MainFolder"), 0)));