Generating XML in bash, need some efficient ideas

6.1k views Asked by At

I need to generate an XML file in bash(I am new to bash/scripting languages, despite working on C/C++/UNIX for some time). Right now, I am generating something like this, which is pretty flat

st='<'
et='>'
sl='/'
-------------------
stag() {
      text=$st$1$et 
      echo $text >> output_file
}
--------------------
etag() {
      text=$sl$1
      stag $text
}
--------------------
attr() {
      text=$1
      echo $text >> output_file
}
--------------------

#--Function Call
stag "tag"
attr "xml"
etag "tag"

--------------------

#--output
<tag>xml</tag>

In this, I feel there are lots of chance to make errors and after coding in C++ for so long, I think there should be a better structured way to code.... Any thoughts is appreciated.... or any material you think, I should learn first, plz post here.... Thanks...

2

There are 2 answers

1
Todd A. Jacobs On BEST ANSWER

You are looking for something like xmlstarlet. The depyx subcommand allows you to convert PYX markup into XML.

This may be sufficient for your prototyping purposes. If not, you'll probably need to look at a more full-featured XML library in Ruby, Python, or Perl.

0
evil otto On

It's usually easier to just quote your strings rather than having to use special variables for special characters, e.g., rather than

text=$st$1$et
echo $text

just use

echo "<$1>"

or printf "<%s>" $1

As for structure, bash does have arrays which you could perhaps use for attributes, but the only way to pass them to functions is by name, and then you have to jump through hoops to get the values:

a=(foo bar baz)
f() {
  eval printf "\${$1[1]}"
}
f a
=> bar