在 bash 中生成 XML,需要一些高效的想法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10884120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:26:22  来源:igfitidea点击:

Generating XML in bash, need some efficient ideas

xmlbashshellxml-generation

提问by howtechstuffworks

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

我需要在 bash 中生成一个 XML 文件(我是 bash/脚本语言的新手,尽管在 C/C++/UNIX 上工作了一段时间)。现在,我正在生成这样的东西,它非常平坦

st='<'
et='>'
sl='/'
-------------------
stag() {
      text=$st$et 
      echo $text >> output_file
}
--------------------
etag() {
      text=$sl
      stag $text
}
--------------------
attr() {
      text=
      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...

在这一点上,我觉得有很多机会犯错误,在用 C++ 编码这么长时间之后,我认为应该有一种更好的结构化方式来编码.... 任何想法都被赞赏.... 或任何你认为的材料,我应该先学习,请在这里发帖....谢谢...

回答by Todd A. Jacobs

You are looking for something like xmlstarlet. The depyxsubcommand allows you to convert PYX markupinto XML.

您正在寻找类似xmlstarlet 的东西。该depyx子命令允许你转换PYX标记成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.

这可能足以满足您的原型设计目的。如果没有,您可能需要查看使用 Ruby、Python 或 Perl 编写的功能更全面的 XML 库。

回答by evil otto

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$et
echo $text

just use

只是使用

echo "<>"

or printf "<%s>" $1

或 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:

至于结构,bash 确实有可以用于属性的数组,但将它们传递给函数的唯一方法是按名称,然后您必须跳过箍以获取值:

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