目标:从csv文件
创建xml文件我正在尝试从csv文件创建一个xml文件,xml包含页眉,页脚和正文。
我创建了3个不同的功能。
输入csv文件
name,value,amt,position,qnty
abc,2,3,4,5
cde,7,8,9,10
abc,12,13,14,15
cde,7,8,9,10
从csv文件
创建xml的代码 #!/usr/bin/sh
FILENAME=$1
#create body of xml file
createBody()
{
echo ${FILENAME}
while read var
do
filename=`echo $var | sed 's/ /_/g'`
echo "<abc:archivingGroup xc:value=\"$var\">" >> ${filename}_Fixings.xml
#create files for each unique group from groups.txt file
grep $var ${FILENAME} > $filename.txt
#traverse each file and create a separate xml file for each group
while IFS=\; read a b c d e
do
TEST=$(cat <<EOF
<abc:index xc:value="$b">
</abc:index>
)
echo $TEST >> ${filename}_Fixings.xml
done < $filename.txt
rm $filename.txt
echo "</abc:archivingGroup>" >> ${filename}_Fixings.xml
done < Groups.txt
}
#header is common is all files
createHeader()
{
filename=$1
Header=$(cat << EOF
<abc:Main>
<abc:sub>
<abc:head>
)
echo $Header > ${filename}_Fixings.xml
}
#footer is common in all files
createFooter()
{
filename=$1;
Footer=$(cat <<EOF
</abc:Main>
</abc:sub>
</abc:head>
)
echo $Footer >> ${filename}_Fixings.xml
}
createarchFile()
{
IFS=\|
#creates the unique groups (abc,cde as per above file)
awk -F";" '{print $1}' ${FILENAME} | sed 1d | sort | uniq > Groups.txt
#add header to each file, each uniq group is treated as a separate file
while read var
do
filename=`echo $var | sed 's/ /_/g'`
createHeader $filename
done < Groups.txt
#create body for all the files , header for all the files is appended above
createBody
#add footer to each file,each uniq group is treated as a separate file
while read var
do
filename=`echo $var | sed 's/ /_/g'`
createFooter $filename
done < Groups.txt
}
createarchFile
上面的代码通过将csv作为输入
来创建一个xml文件这是正确的方法还是有其他方法来创建xml?
答案 0 :(得分:0)
使用printf
填写值可能是一个更清晰的选择。
在外部循环上构建第一个标记为
first_tag='<abc:archivingGroup xc:value="%s">
%s
</abc:archivingGroup>'
var='some_filename'
first_tag=$(printf "$first_tag" "$var" "%s")
first_tag将包含
<abc:archivingGroup xc:value="some_filename">
%s
</abc:archivingGroup>
在内部循环上使用该格式化字符串
#format element including placeholder for next element (if any)
ele='<abc:index xc:value="%s" />
%s'
ele=$(printf "$ele" "$b" "%s")
# add to first_tag
first-tag=$(printf "$first_tag" "$ele" "%s")
结果
<abc:archivingGroup xc:value="some_file_name">
<abc:index xc:value="abc" />
%s
</abc:archivingGroup>
只要有占位符,就可以添加更多元素。