html

Automatically convert XML to HTML with xsltproc and bash in Linux

After doing nmap, I often convert the XML output to HTML to view in browser.


xsltproc input.xml -o output.html

However, if I want to convert multiple xml files to html, I’ll have to type the command multiple times. That’s rediculously tiredsome. So I decide to write a simple bash file to automatically convert all the xml files in a folder into html files with the same names.

Example:

you have following files in /some_folder/


user@linux: ~/some_folder/ls

File1.xml  File2.xml  File3.xml

After running the script, you will have the following file


user@linux:~/some_folder/convert_xml.sh

File1.xml to File1.html

File2.xml to File2.html

File3.xml to File3.html

Don’t worry, the old fils are still there.

Here is my code. It is very basic, does not have the “-help” option, but it will do the work. You can convert directories other than the current directory by input while calling the script, like this:


user@linux: ~/ convert_xml.sh  /some_dir/some_dir/some_dir

The code

#!/bin/bash
#convert all xml to html with the same name
# $1 = directory

#INTIALIZE VARIABLES
p_directory="file_directory"
file_list="file_list"

#GET DIRECTORY
if [ $# -eq 0 ]
then
p_directory="./" #get director=./ if no directory is inputed

elif [ $# -eq 1 ]
then
p_directory=$1
#ADD "/" to the end of the directory
if [ "${p_directory: -1}" != "/" ]
then
p_directory="$p_directory/"
fi

elif [ $# -gt 1 ]
then
echo \*ERROR\*
echo Input only the directory
exit 1
fi

#GET FILE_LIST
file_list=$(find $p_directory -type f -name "*.xml")

#DO THE WORK
echo "Directory: $p_directory"

for file in $(echo $file_list);
do
p_full_name=$(basename $file)
p_file_name="${p_full_name%.*}"

xsltproc $p_directory$p_full_name -o $p_directory$p_file_name.html
echo "Convert $p_full_name to $p_file_name.html"

done

#remove var
unset file_list
unset p_directory

I’m pretty sure that there are more simple way to do this, but in the mean time, this is what I can come up with. Hope it is of some help to you. And if you have any suggestion, I’m all ear.

You can download the script file here https://www.mediafire.com/?lqr9d34pd1q7g9t

Advertisements