2010-01-21 72 views
0

我想将一个驱动器索引到一个xml文件。我的可怜的尝试是这样的:创建xdocument结构

 internal static void createIndex(String path, String driveLabel) 
     { 

      XDocument w = new XDocument(); 
      w.Add(createStructure(path, new XElement("root"))); 
      w.Save(driveLabel +".xml"); 
     } 

     internal static XElement createStructure(String path, XElement x) 
     { 
      try 
      { 
       String[] files = Directory.GetFiles(path); 
       String[] folders = Directory.GetDirectories(path); 

       foreach (String s in folders) 
       { 
        x.Add("directory", createStructure(s, x)); 
       } 

       foreach (String f in files) 
       { 
        x.Add(new XElement("file", f)); 
       }  
      } 
      catch (Exception e) { } 

      return x; 
     } 

一些输出这里 - 简单的文件结构 - 根有2个MP3和包含2个文件1个文件夹。

<?xml version="1.0" encoding="utf-8"?> 
    <root> 
    <file>E:\.wd_tv\ph.db</file> 
    <file>E:\.wd_tv\ph.db-journal</file>directory<root> 
    <file>E:\.wd_tv\ph.db</file> 
    <file>E:\.wd_tv\ph.db-journal</file>directory</root> 
    <file>E:\180.mp3</file> 
    <file>E:\181.mp3</file> 
    </root> 

我收到了一些奇怪的混合标记那里,我根本不明白它。任何帮助赞赏。使用OD的循环结构

,变更成:

<?xml version="1.0" encoding="utf-8"?> 
<root>directory<root>directory</root> 
    <file>E:\180.mp3</file> 
    <file>E:\181.mp3</file> 
</root> 
+0

你越来越hoodywha?抛出一些错误的输出,因为代码看起来是正确的。 – Will 2010-01-21 13:51:45

回答

1

试试下面的循环结构:

 foreach (String s in folders) 
     { 
      x.Add("directory", createStructure(s, x)); 
      foreach (String f in files) 
      { 
       x.Add(new XElement("file", f)); 
      } 
     } 

这样,您将显示属于目录中的目录后,立刻将文件在里面。