如何使用xmllint和xpath输出多行

时间:2013-06-13 16:58:43

标签: bash xpath xmllint

我正在编写一个简单的bash脚本来解析一些xml。我使用的是sed和awk,但我认为xmllint更适合。

不幸的是,我对xpath完全不熟悉,所以我真的很努力。

我正在尝试使用以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<releaseNote>
<name>APPLICATION_ercc2</name>
<change>
  <date hour="11" day="10" second="21" year="2013" month="0" minute="47"/>
  <submitter>Automatically Generated</submitter>
  <description>ReleaseNote Created</description>
</change>
<change>
  <version>2</version>
  <date hour="11" day="10" second="25" year="2013" month="1" minute="47"/>
  <submitter>fred.bloggs</submitter>
  <description> first version</description>
<install/>
</change>
<change>
  <version>3</version>
  <date hour="12" day="10" second="34" year="2013" month="1" minute="2"/>
  <submitter>fred.bloggs</submitter>
  <description> tweaks</description>
<install/>
</change>
<change>
  <version>4</version>
  <date hour="15" day="10" second="52" year="2013" month="1" minute="38"/>
  <submitter>fred.bloggs</submitter>
  <description> fixed missing image, dummy user, etc</description>
  <install/>
</change>
<change>
  <version>5</version>
  <date hour="17" day="10" second="31" year="2013" month="1" minute="40"/>
  <submitter>fred.bloggs</submitter>
  <description> fixed auth filter and added multi opco stuff</description>
  <install/>
</change>

.....

并处理它以将'3'作为变量传递给xpath脚本,并输出如下内容:

4    fred.bloggs    10/1/2013 15:38     fixed missing image, dummy user, etc
5    fred.bloggs    10/1/2013 17:40     fixed auth filter and added multi opco stuff

换句话说,每个节点内容的复杂组合,其中版本的值大于,例如,3。

1 个答案:

答案 0 :(得分:3)

虽然使用xpath工具可能不那么特殊,但您可能会发现有一种对此类事物有用的工具是xmlstarlet

使用xmlstarlet,以下工作(我为您的示例添加了releaseNote的关闭标记):

$ summary() {
  xmlstarlet sel -t -m "//change[version > $2]" \
                    -v submitter -o $'\t' \
                    -v date/@day -o '/' -v date/@month -o '/' -v date/@year -o ' ' \
                    -v date/@hour -o ':' -v date/@minute -o $'\t' \
                    -v description -n $1
}
$ summary test.xml 3
fred.bloggs     10/1/2013 15:38  fixed missing image, dummy user, etc
fred.bloggs     10/1/2013 17:40  fixed auth filter and added multi opco stuff

$