Skip to content

Commit b5e07d1

Browse files
author
Giles Westwood
committed
add xml pretty function
1 parent fd495bb commit b5e07d1

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

lib/xml.sh

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
sk-xml-to-txt() {
2+
sk_help "Usage: cat xml | $FUNCNAME RecordTagName Field1 Field2 ...." "$@" && return
3+
local tag=$1; shift
4+
local fields=""; fields="$@" # zsh compatible
5+
cat - >/tmp/xmloutput.$$
6+
if ! grep -q '<' /tmp/xmloutput.$$ ;then
7+
echo "WARNING: non xml response detected"
8+
cat /tmp/xmloutput.$$
9+
rm /tmp/xmloutput.$$ 2>/dev/null
10+
return
11+
fi
12+
13+
cat /tmp/xmloutput.$$ | xmllint --format - | perl -ne '
14+
BEGIN {
15+
@recs = %rec= ();
16+
$tag = shift @ARGV;
17+
@fields = split(qq| |,shift @ARGV);
18+
};
19+
m|<$tag>| ... m|</$tag>| or next;
20+
if (m|<$tag>|) { %rec = (); next; }
21+
if (m|</$tag>|) { push(@recs,{%rec}); next; }
22+
m|<(\w+)>([^<]+)| and $rec{$1} = $2;
23+
END {
24+
for $r (@recs) {
25+
@_ = ();
26+
for $f (@fields) { push(@_,$r->{$f}); }
27+
print join(qq| |,@_).qq|\n| if @_;
28+
}
29+
};
30+
' "$tag" "$fields"
31+
rm /tmp/xmloutput.$$ 2>/dev/null
32+
}
33+
34+
sk-xml-pretty(){
35+
sk-pack-install -b xmllint -p libxml2-utils
36+
xmllint --format "$@"
37+
}
38+

0 commit comments

Comments
 (0)