Bash脚本和xml / rss解析

时间:2012-05-11 13:04:04

标签: xml bash parsing xml-parsing xmllint

我正在编写一个使用xmllint解析rss的小脚本。

现在我使用以下命令获取标题列表:

ITEMS=`echo "cat //title" | xmllint --shell rss.xml `
echo $ITEMS > tmpfile

但它返回:

<title>xxx</title> ------- <title>yyy :)</title> ------- <title>zzzzzz</title>

没有换行符或空格。 现在我只对标题标签的文本内容感兴趣,如果可能的话,我想使用for / while循环浏览标题,例如:

for  val in $ITEMS 
do
       echo $val
done

怎么做? 提前致谢

3 个答案:

答案 0 :(得分:4)

我在某些时候有相同类型的要求在bash中解析xml。我最终使用了你可以安装的xmlstarlet http://xmlstar.sourceforge.net/

如果没有,类似的东西将删除周围的标签:

echo "cat  //title/text()" | xmllint --shell  rss.xml

然后你需要在管道输出后清理输出,一个基本的解决方案是:

echo "cat  //title/text()" | xmllint --shell  rss.xml  | egrep '^\w'

希望这有帮助

答案 1 :(得分:2)

要回答您的第一个问题,$ITEMSecho的不加引号的使用正在消除您的新行字符。试试

ITEMS=`echo "cat //title" | xmllint --shell rss.xml `
echo "$ITEMS" > tmpfile
#----^------^--- dbl-quotes only

通常,使用for循环最好留给不会产生意外空格或其他不可打印字符的项目。 (非字母数字),如for i in {1..10} ; do echo $i; done

你真的不需要变量或tempfile,试试

  echo "cat //title" | xmllint --shell rss.xml |
  while read line ; do
      echo "$line"
  done

根据您的rrs Feed中的内容,您还可以从更改读取cmd使用的默认IFS(内部字段分隔符)中受益,尝试

while IFS= read line ....
# or 
while IFS="\n" read line
# or
while IFS="\r\n" read line

我不确定你试图通过echo "cat //title" |进入xmllint实现什么,所以我将其保留原样。这是对xmllint的指令吗?或者是通过它来创建文档的标题? (现在没有xmllint到expermient)。

此外,您可能希望查看reading rss feeds with awk,但它的级别相当低。

我希望这会有所帮助。

答案 2 :(得分:0)

除了Philippe's answer外,如果您想直接从 {} 之类的命令获取xml输出 >,您可以使用another file descriptor对其进行管道传输。

实际上,def create_grid(): return [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] def print_grid(grid): print("\n".join( " ".join(map(str, row)) for row in grid )) print_grid(create_grid()) shell输入已经使用了STDIN。在一个有效的示例下方(只需记住用您的URL参数代替)。

cURL