# Directory structure to xml - display in flex tree

**URL:** <https://www.ruby-forum.com/t/directory-structure-to-xml-display-in-flex-tree/145440>\
**Category:** Rails\
**Created:** [August 9, 2008, 11:59am UTC](https://www.ruby-forum.com/t/directory-structure-to-xml-display-in-flex-tree/145440 "2008-08-09T11:59:59Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![shailendra-kamath](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/48db29/32.png) [@shailendra-kamath](https://www.ruby-forum.com/u/shailendra-kamath)\
**Post date:** [August 9, 2008, 11:59am UTC](https://www.ruby-forum.com/t/directory-structure-to-xml-display-in-flex-tree/145440/1 "2008-08-09T11:59:59Z")

</div>

Below code can be used to convert directory structure in xml.

require ‘rubygems’  
require ‘rexml/document’

class DirectoryStructure  
@@excludes = ["…","."]  
@@doc = REXML::Document.new %{ \<?xml version="1.0" encoding="UTF-8" ?\> }

def self.traverse\_directory(root\_path)

#traverse initial directory structure  
folder = @@doc.add\_element( ‘myroot’,{‘id’ =\> root\_path} )

#call loop\_path with root\_path and parent\_node  
loop\_path(root\_path,folder)  
#create xml file  
open( “final\_directory\_structure.xml”, “w” ) do |f|  
f.puts @@doc  
end

end

def self.loop\_path(path,parent\_node)

dir\_entries= Dir.entries(path)

# don’t need ‘.’,’…’

dir\_entries = dir\_entries-[’.’,’…’]

dir\_entries.each do | entry |

# check if directory or file

if File.directory?(path+"/"+entry)

#Folders Loop -------------------------------------------------  
#Gets the directories of the current node.  
#It changes for each recursive call  
folder = parent\_node.add\_element( ‘folder’ ,{‘label’ =\>entry  
,‘file\_path’ =\> path+"/"+entry } )  
loop\_path( path+"/"+entry, folder )  
else  
#Files Loop ------------------------------------------------------  
file = parent\_node.add\_element( ‘file’ ,{‘label’ =\>entry ,‘file\_path’  
=\> path+"/"+entry } )

end

end

end

#first call to traverse directory  
self.traverse\_directory(“Authentication/Authentication”)

end
