Search code examples
c#xmlxmldocumentdirectoryentryxmldom

Create XML DOM of a Directory structure


If got a method that returns a treenode based upon a Directory

 private static TreeNode GetDirectoryNodes(string path)
        {
            var dir = new DirectoryInfo(path);
            var node = new TreeNode(dir.Name);
            foreach (var directory in dir.GetDirectories())
            {
                node.Nodes.Add(GetDirectoryNodes(path + "\\" + directory.ToString()));
            }
            return node;
        }

However I need to create an XML DOM of the directory stucture, However I am new to XML DOM and can't figure out how to do this. Problems that I see are: how to get \ into the XML; and how to get Subdirectories This is what I've got so far

private static XmlDocument GetDirTreeData(string path)
        {
            var dir = new DirectoryInfo(path);
            XmlDocument XMLDOM = new XmlDocument();
            XmlElement xl = XMLDOM.CreateElement(path);
            foreach (var directory in dir.GetDirectories())
            {
                xl.InnerXml = directory.ToString();
            }
            return XMLDOM;
        } 

Solution

  • Take a look at LINQ to XML. It is easier to accomplish your task with LINQ. Here is a code that works, but does not handle Access denied and similar issues

    static void Main(string[] args)
        {
            XDocument xdoc = new XDocument(
                new XElement("Root",
                    DirToXml(new DirectoryInfo("C:\\MyFolder"))));
        }
    
        private static XElement DirToXml(DirectoryInfo dir)
        {
            return new XElement("Directory",
                        new XAttribute("Name", dir.Name),
                        dir.GetDirectories().Select(d => DirToXml(d)));
        }
    

    xdoc variable is your xml document. DirToXml is recursive method that finds all subdirectories and creates elements for each of them.

    The results looks like this:

    <Root>
      <Directory Name=".history">
        <Directory Name="0" /> 
        <Directory Name="1" /> 
        <Directory Name="10" /> 
        <Directory Name="11" /> 
        <Directory Name="12" /> 
        <Directory Name="13" /> 
        <Directory Name="14" /> 
        <Directory Name="15" /> 
        <Directory Name="16" /> 
      </Directory>
    </Root>