开发者

creating xdocument structure

I am trying to index a drive to a xml file. My pitiful attempt is this:

        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;
        }

some output here - simple file structure - root has 2 mp3s and 1 folder containing开发者_开发技巧 the 2 files.

 <?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>

I am getting some strangely intermixed tags there and I simply don't get it. Any help appreciated.

using od's loop structure it changes to that:

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


Try the following looping structure:

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

This way you will display the files belonging to a directory immediatly after the directories in it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜