格式,并在bash结合的XPath输出 [英] Format and combine output of xpath in bash
本文介绍了格式,并在bash结合的XPath输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用bash的工具的XPath
来解析这个XML输入:
I'm trying to parse this xml input using the bash utility xpath
:
<?xml version="1.0" encoding="UTF-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<entry>
<title>Title 1</title>
<author>Author 1</author>
</entry>
<entry>
<title>Title 2</title>
<author>Author 2</author>
</entry>
</feed>
我需要这种格式输出:
I need an output in this format:
1. Title: Title 1
Author: Author 1
2. Title: Title 2
Author: Author 2
我(仅使用单个的XPath
命令,或至多3-4命令)周围很多试图以简单的方式来实现这一摆弄,但所有我的努力都是徒劳的。任何人都可以请帮我这个?
I've fiddled around a lot trying to achieve this in a simple way (using only a single xpath
command, or at most 3-4 commands), but all my efforts have been in vain. Could anyone please help me out with this?
推荐答案
猛砸版
#!/bin/bash
count=1
input=input.xml
while [ -n "$title" -o $count = 1 ]
do
title=`cat $input | xpath //entry[$count]/title 2>/dev/null | sed s/\<title\>//g| sed s/\<\\\\/title\>//g`
author=`cat $input | xpath //entry[$count]/author 2>/dev/null | sed s/\<author\>//g| sed s/\<\\\\/author\>//g`
if [ "$title" -a "$author" ]; then
echo $count $title $author
fi
count=$((count+1))
done
Perl版本(未经测试)...
Perl version (untested) ...
#!/usr/bin/perl
use XML::XPath;
my $file = 'input.xml';
my $xp = XML::XPath->new(filename => $file);
my $count = 1;
foreach my $entry ($xp->find('//entry')->get_nodelist){
print $count;
print 'Title:' . $entry->find('title')->string_value;
print 'Author: ' . $entry->find('author');
$count++;
}
这篇关于格式,并在bash结合的XPath输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文