65.9K
CodeProject is changing. Read more.
Home

Treeview-creating a treeview of folder structure using javascript ,xsl and .net

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.87/5 (7 votes)

Feb 19, 2007

7 min read

viewsIcon

48012

downloadIcon

475

Creating on fly treeview of folder structure by genrating dynamic xml using asp.net ,this xml is transformed using xslt and following user navigation using javascript.

Introduction

This is my first article to code project, its been more than 3 months following the articles I felt interesting the way everyone submitting the articles ,I feel the time has come to submit an article which will be helpful to naive developers.I here presenting an article which involves vb coding, xml generation ,using xslt and javascript .

Before wetting our foot with coding I want to give bird's eye of whats this article about.

There was a requirement like showing a tree view of folder structure which is very fickle(mean folder structure is changing), when ever user hits the page he must be viewed with latest folders ,documents etc., present in system(server) should be viewed. To keep up the requirement I used xml which will be generated on the fly when user hits the page and to beautify the front end we used xslt and javascript to follow user navigation in front end.I would explain the objects used with respect to code.

Using the code

Prerequisites for following the code a small pinch of knowledge about javascript,xslt and bit more experience on visual basics.
here I go first with namespaces used in this application.



imports system.xml
imports system.xml.xsl
imports system.text
imports system.io

These are namespaces used for accessing system directory objects and xml objects.
(File Path and other variables naming conventions are not been standardized)
Dim tw As XmlTextWriter
tw = New XmlTextWriter("C:\\test\test12345" & ".xml", _
New System.Text.UTF8Encoding())

tw.Formatting = Formatting.Indented
'tw.Indentation = 4

' Write out the header information
tw.WriteStartDocument()
'starting the xml with tag name "folders" you can change it to other 'but change correspondingly in xslt file also
tw.WriteStartElement("FOLDERS")'starting the xml with tag name "folder" you can change it to other 'but change correspondingly in xslt file also
tw.WriteStartElement("FOLDER")
tw.WriteAttributeString("name", "Knowledge Tree")
tw.WriteStartElement("FOLDER")
tw.WriteAttributeString("name", "Certification Material")

In the above code declared a object to a class xmltextwriter which accepts a xml file location as argument(constructor) .This object has properties like formatting ,indentation for generating valid xml of version-1 and encoding="utf-8" there by following method 'writestartdocument' which starts xml document,before we go further I will explain when to which method of xmltextwriter starting with WriteElementString it will output with text between the tags(<title>Enter status of bug for search</title>) it accepts arguments two arguments tag name and text to be displayed(tw.WriteElementString("title", "Enter status of bug for search")),of course we didn't use in code it will be helpful,coming to WriteStartElement using which we can starts new tag(<folder>) there must corresponding end element using writeendelement(</folder) this tag pretty trickery, if this tag don't have any child elements(another writestartelement) this will be self ending tag. If it has another writestartelement( before writeendelement) this will become parent tag.

Iam using recursive function for digging the directory.where below function is self explanatory which calls itself until filesysteminfo is not a directory(filesysteminfo.name<>directory)., otherwise(.doc,.txt ) it ends as leaf.




Function fileinfo(ByVal strfilepath As String) As Collection
Dim colinner As New Collection
'declaring Directoryinfo object to get the file information stored 'in system
Dim dfinner As DirectoryInfo
'passing the Parent file path(in which other files are stored), 'giving all access to parent directory in order to avoid security 'exception
dfinner = New DirectoryInfo(strfilepath)
Dim fsiinner As FileSystemInfo
For Each fsiinner In dfinner.GetFileSystemInfos
'collecting all directory information pres
colinner.Add(fsiinner)

Next
Dim countinner As Integer = colinner.Count()
Dim tempdocinner As Integer = 0
For tempdocinner = 1 To countinner
Dim strtest1
strtest1 = colinner.Item(tempdocinner)
'retrieving the type of elements stored in collection
Dim strtype As Type = strtest1.GetType()
If strtype.Name = "DirectoryInfo" Then
Dim strfilename As DirectoryInfo = colinner.Item(tempdocinner)
'starting the xml with tag "folder".
'if change this tag name then change in xslt file also
tw.WriteStartElement("FOLDER")
tw.WriteAttributeString("name", prodnode.Text)

Dim strpathtemp = strfilepath & strtest1.name & "/"
'since it is directory calling the function fileinfo(with file 'path as argument)
fileinfo(strpathtemp)
tw.WriteEndElement()
Else
'coming to else part when gettype of collection(
colinner) is not a 'directory
'it means some .doc or .pdf or .ppt etc
Dim files As FileInfo
files = colinner.Item(tempdocinner)
Dim strpath = files.FullName
prodnode = New TreeNode
prodnode.Text = files.Name
Dim strdocname As String = prodnode.Text
tw.WriteStartElement("KEY")
tw.WriteAttributeString("name", prodnode.Text)
tw.WriteAttributeString("path", strpath)

tw.WriteEndElement()

nodeSupp.ChildNodes.Add(prodnode)
End If
'tw.WriteEndElement()
Next

Return colinner
End Function

Then coming to IO objects let me elucidate with respect to code,(Sorry for my impatience in following Coding Standards.)



Dim strfileinfopath As String = System.AppDomain.CurrentDomain.BaseDirectory & "docs/"
Dim df As DirectoryInfo
'geting the directory information by passing directory path as 'argument
df = New DirectoryInfo(strfileinfopath)
Dim fsi As FileSystemInfo
Dim col As New Collection
Dim colfilepath As New Collection
Dim colfilename As New Hashtable
'collecting all filesystem information present in parent folder

For Each fsi In df.GetFileSystemInfos
Dim shi = fsi
col.Add(fsi)
Next
Dim docfilescoun As Integer = col.Count()
Dim tempdoc As Integer = 0
Dim strfileinfo As DirectoryInfo
If docfilescoun > 0 Then
For tempdoc = 1 To docfilescoun
strfileinfo = col.Item(tempdoc)
Dim strtest
strtest = col.Item(tempdoc)
'geting the type of the items of collection(
col)
Dim strtype As Type = strtest.GetType
'if the type is directoryinfo continue(repeating the process of 'checking the subfolders) since it may contain subfolders by 'calling 'function fileinfo with path of folder to be checked
If strtype.Name = "DirectoryInfo" Then
Dim filecollection As New Collection
'using fullname property of fileinfo object to get the path of 'that file
Dim strfullname As String = strfileinfo.FullName
Dim strfilename1 As String = strfileinfo.Name
Dim strfileinnerpath As String = System.AppDomain.CurrentDomain.BaseDirectory & "docs/" & strfilename1 & "/"
'starting the xml with tag name "folder" you can change it to other 'but change correspondingly in xslt file also
tw.WriteStartElement("FOLDER")
tw.WriteAttributeString("name", strfilename1)

'testmaterial is a my local directory folder

If strfileinfo.Name <> "
testmaterial " Then
filecollection = fileinfo(strfileinnerpath)
End If
tw.WriteEndElement()
Else
'coming to else part means not a item in collection(col) is not a 'directory it is of .doc or .pdf or .ppt etc.m
Dim filename As FileInfo
filename = col.Item(tempdoc)
Dim strfull As String = filename.FullName
tw.WriteStartElement("
KEY")
tw.WriteAttributeString("
name", filename.Name)
tw.WriteAttributeString("
Path", strfull)
tw.WriteEndElement()
End If
Next
' closing all the nodes correspondingly
tw.WriteEndElement()
tw.WriteEndElement()
tw.WriteEndElement()
tw.WriteEndDocument()
'diposing all the object of xml
tw.Flush()
tw.Close()
End If

Starting with System.AppDomain.CurrentDomain.BaseDirectory which returns path of base directory of your application as it developed in vs.net in this case returns "C://inetpub/wwwroot/treeview".coming to DirectoryInfo class which returns all the directory information about the path passed as argument.

in this for loop "fsi" is object of filesysteminfo class ,where getfilesysteminfos is a method of derectoryinfo which returns files or directory information for each of type filesysteminfo




For Each fsi In df.GetFileSystemInfos
Dim shi = fsi
col.Add(fsi)
Next

Here we are calling fileinfo function because it is directory(I mean it is file which may contain sub folders in which contain documents or sub folders)

filecollection = fileinfo(strfileinnerpath)

Coming to crux path applying xslt to xml

Dim doc As New XmlDocument()

doc.Load(Server.MapPath("test12345.xml"))

Dim t As New XslTransform()
t.Load(Server.MapPath("images/XSLTFile1.xslt"))
Dim sb As New StringBuilder()
Dim writer As TextWriter
writer = New StringWriter(sb)

'vvvvvvimp
'if the framework is older add "nothing" as one more argument to 'below t.transform like t.Transform(doc, Nothing, writer, Nothing)
'vvvvimp


t.Transform(doc, Nothing, writer)
Label1.Text = sb.ToString()
}



In the above block of code loading the xml document using server.mappath and applying xslt to xml using XslTransform class.



I am ending this article with giving code(this code is need more parsed to xml ) how to read ,you can skip this if know how to read xml document or having knowledge about xmltextreader class.



Dim oRead As XmlTextReader
Dim cou As Integer = 1

Try
oRead = New XmlTextReader("C:\inetpub\wwwroot\test\test12345.xml")
Do While oRead.Read
oRead.MoveToContent()
If oRead.Name.Equals("KEY") Then

If oRead.GetAttribute("name").ToString = lsStatus Then
Dim strpath As String = oRead.GetAttribute("path")
Dim stractpath = Split(strpath, "test\")
Dim stractpath1 = stractpath(1)
'redirecting to viewfile.aspx for viewing the file selected with 'path as querystring
Response.Redirect("viewfile.aspx?filename=" + stractpath1)
End If
End If

Loop

I here conclude this article with the whole code contains just three objects

1.directoryinfo
2.xmltextwriter
3.xsltransform
4.xmltextreader

I mean to say nothing to daunt just playing around those four objects and calling a function recursively.

ABOUT DOWNLOAD.

application presented in zip file is compatible to v1.1 and visual studio 2003.