【问题标题】:Format and combine output of xpath in bash在bash中格式化和组合xpath的输出
【发布时间】:2011-08-03 11:59:32
【问题描述】:

我正在尝试使用 bash 实用程序 xpath 解析此 xml 输入:

<?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>

我需要这种格式的输出:

1. Title: Title 1
   Author: Author 1
2. Title: Title 2
   Author: Author 2

为了以一种简单的方式(仅使用一个 xpath 命令,或最多 3-4 个命令)实现这一目标,我做了很多尝试,但我所有的努力都是徒劳的。谁能帮我解决这个问题?

【问题讨论】:

  • XPath 从 XML 树实例中选择 节点。 它不序列化

标签: xml bash xpath xml-parsing


【解决方案1】:

Bash 版本

#!/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 版本(未经测试)...

#!/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++;
}

【讨论】:

  • 我正在制作一个 shell 脚本,但对 Perl 一无所知。我需要知道如何在 bash 中使用xpath 命令来解决问题。
  • 我想出了一个(类似的)解决方案。谢谢:)
  • @vicky 如果这个答案接近你的想法 - 你应该考虑接受@qwerty 的答案以承认他们付出的努力(即使你没有按原样采用他们的答案)跨度>
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多