1
我想創建一個類似如下目錄創建的XDocument Stucture
<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>
我不使用目錄結構的XMLDOM如果我特林做的工作,但下面的代碼給出了一個錯誤說法我特林輸入非法字符
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)));
+1發送的OP正確的道路,感謝亨克! –
謝謝,現在我只是得到它的工作遞歸,但我知道我可以做'dir.GetDirectories(「*」,System.IO.SearchOption.AllDirectories);'我知道這是問題的側面,但你知道嗎無論如何將輸出應用於XElement,但仍然有level元素標籤? –
請參閱編輯。 @SamStephenson –