Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write XML from delimited file

Status
Not open for further replies.

aforstie

Programmer
Jun 19, 2006
19
US
I have a multi-line pipe delimited file that I want to use to write an XML document. I was hoping to use a shell script to do this. Does anyone have any examples or advice they are willing to share.

Here is what the pipe delimited file would look like:
Name1|PHX|AZ|
.
.
.
Name5|MSP|MN

Here is what I would want the xml to look like:
<parent-element>
<place name="Name1">
<location city="PHX" state="AZ"/>
</place>
.
.
.
<place name="Name5">
<location city="MSP" state="MN"/>
</place>
</parent-element>

My plan was to read the file in and try to parse the file line by line. I thought that I could use "while read line" and then use the cut command to build the xml. But this approach appears to require that I specify a file for the cut command and the it runs on the whole file and not the link of the file.

FILE="$1"

# make sure file exists and is readable
if [ "$1" == "" ]; then
echo "Specify input file"
exit 1
elif [ ! -f $FILE ]; then
echo "$FILE : does not exist"
exit 2
elif [ ! -r $FILE ]; then
echo "Cannot read: $FILE"
exit 3
fi

echo "<?xml version= \"1.0\" encoding= \"utf-8\"?>"
echo "<parent-element>"
exec 0<$FILE
while read line
do
# cut -f4 -d\|
# if this works, just use it below as applicable
echo " <place name=\"\">"
echo " <location city=\"\" state=\"\">"
echo " </place>"
done
echo "</parent-element>
 
You can change the field separator that the shell uses, like so
Code:
IFS="|"
while read name city state
   do
      echo "   <place name=\"$name\">"
      echo "      <location city=\"$city\" state=\"$state\">"
      echo "   </place>"
   done
echo "</parent-element>"

--
 
Interesting. That is exactly what I was looking for and it worked great. Thanks for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top