xml - Format and combine output of xpath in bash -
i'm trying parse xml input using 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 output in format:
1. title: title 1 author: author 1 2. title: title 2 author: author 2 i've fiddled around lot trying achieve in simple way (using single xpath command, or @ 3-4 commands), efforts have been in vain. please me out this?
bash version
#!/bin/bash count=1 input=input.xml while [ -n "$title" -o $count = 1 ] 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" ]; echo $count $title $author fi count=$((count+1)) done perl version (untested) ...
#!/usr/bin/perl use xml::xpath; $file = 'input.xml'; $xp = xml::xpath->new(filename => $file); $count = 1; foreach $entry ($xp->find('//entry')->get_nodelist){ print $count; print 'title:' . $entry->find('title')->string_value; print 'author: ' . $entry->find('author'); $count++; }
Comments
Post a Comment