Wednesday 6 October 2021

How to Read XML Files From A Directory Golang

Getting Specific Files from a directory by manually can be hard but it can be more hard when you know that there is thousands of and you have to choose only specific extension file. So How do we make it simple to file specific files from directory, So there is the simple answer programming. How? Just Write an script which reads the top level files from a directory and check the extensions of each file, If that file contains the same extension as you wanted then here you go. It's easy to say it in words, so let's start writing some code so you guys can have idea of it..



1. Load Required Flags/Arguments.

We're about to use few flags for this program which is help us to use targeted repository/direcotry full path. We're going to use flags package.

1. First we've loaded the package we're not using go mod so that why we're using direct main package
2. We've created a struct which will going to hold the path of the directory from which we've to extract all the XML files.
3. Created a function loadFlags which have flags package used and that function return the Flag struct with the path value in it.
3. From Line Number 23-30 calling the main function and in the main function we're calling loadFlags function which returns the Flag struct



2. Open Direcotry.

For Opening Folder We're going to use the os package which is inbuild package of Golang

In OpenDir function we're opening the directory by calling the os.Open function if it fails then it will going to return the error other the *os.File which holds information about the file and folders.



3. Get Files and Folder From Directory.

In checkFilesinDir function we're checking for the files and folder inside root path and then after getting any file and folder we're directly appending that value inside a array/slice and then reutring it.



4. Look for Xml files.

Next Step is to check for the xml files array

We've created another function which iterates the loop over the slice of string and check for the .xml extension if any file contains .xml that values will store in the xmlfiles variable, and then returning that back



5. Combine All Functions

Combining all the function into single function and then will going to call this function in the main function.



6. Full Code:

OUTPUT:

Labels: , , , ,

0 Comments:

Post a Comment

If have any queries lemme know

Subscribe to Post Comments [Atom]

<< Home