简体   繁体   English

Shell脚本,解析XML片段

[英]Shell script, parse XML snippet

In a shell script (Linux, bash, #!/bin/sh) I have a variable containing XML data like this: 在shell脚本(Linux,bash,#!/ bin / sh)中,我有一个包含XML数据的变量,如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<interface>
    <objects retrieved="0" total="0"/>
</interface>

Some error handling is already done when getting this data, so focus on the actual question please. 获取此数据时已经完成了一些错误处理,请关注实际问题。 And the question is: easy/effective way of reading the "objects" element's attribute data (named "retrieved"). 问题是:简单/有效地读取“对象”元素的属性数据(命名为“已检索”)。 It can be 0 or 1. (and nothing else). 它可以是0或1.(没有别的)。 I guess I have two options: regular expressions and XML-parsing with some external program. 我想我有两个选择:正则表达式和一些外部程序的XML解析。 But which one should I choose? 但我应该选择哪一个? Thanks in advance. 提前致谢。

You can use xmlstarlet to get the attr: 您可以使用xmlstarlet来获取attr:

$ xmlstarlet sel -t -m //objects -v @retrieved input.xml
0

Or 要么

$ xmlstarlet sel -t -m //objects/@retrieved -v . input.xml

-m or --match <xpath>     - match XPATH expression
-v or --value-of <xpath>  - print value of XPATH expression

Both are good choices, If you want strict choice that your script should be independent of external programs, I think Using regular expressions is better. 两者都是不错的选择,如果你想严格选择你的脚本应该独立于外部程序,我认为使用正则表达式会更好。 Using regular expression may make the program function more faster than using an external program. 使用正则表达式可以使程序功能比使用外部程序更快。

But using regular expression is not always a feasible option, especially when you have less time, and the regular expression you are making is complex. 但是使用正则表达式并不总是一个可行的选择,特别是当你的时间较少时,你正在制作的正则表达式很复杂。 External program is an option then only. 外部程序只是一个选项。 If you plan to move this script to another computer, this external program may cause dependecy or an overhead. 如果您计划将此脚本移动到另一台计算机,则此外部程序可能会导致依赖性或开销。

I will suggest Regular expressions. 我会建议正则表达式。 These may help you. 这些可能对你有帮助。 Take a look. 看一看。

How to parse XML using shellscript? 如何使用shellscript解析XML?

  • This is really helpful 这真的很有帮助

And this have some idea in the content. 这在内容中有一些想法。

http://silveiraneto.net/2010/05/13/substitution-on-a-xml-file-shell-script-snippet/ http://silveiraneto.net/2010/05/13/substitution-on-a-xml-file-shell-script-snippet/

Here's a function which will convert XML name-value pairs and attributes into bash variables. 这是一个将XML名称 - 值对和属性转换为bash变量的函数。

http://www.humbug.in/2010/parse-simple-xml-files-using-bash-extract-name-value-pairs-and-attributes/ http://www.humbug.in/2010/parse-simple-xml-files-using-bash-extract-name-value-pairs-and-attributes/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM