WJG (14/11/21)
Needed to find a reliable way of extracting values from a largish XML database (48Mb). This was the quickest and simplest way of solving the problem. The sample data was obtained from https://www.w3schools.com/xml/cd_catalog.xml.
======
DECCA
9.90
1991
The dock of the bay
Otis Redding
USA
Stax Records
7.90
1968
Picture book
Simply Red
EU
Elektra
7.20
1985
Red
The Communards
UK
London
7.80
1987
Unchain my heart
Joe Cocker
USA
EMI
8.20
1987
======
======
# !/bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" "$@"
package require tdom
package require json
set fp [open cd_catalog.xml r]
set XML [read $fp]
close $fp
## Convert set XML formatted data to a Tcl dict
# use tdom to convert XML to JSON
# use json to convert JSON to dict
# @param[in] xml the xml text to convert
# returns data in xml as an enumberated dict
proc xml2dict { xml } {
set root [[dom parse $xml] documentElement]
set i -1
foreach node [$root childNodes] { lappend res [incr i] [::json::json2dict [$node asJSON] ] }
return $res
}
set DICT [xml2dict $XML]
puts [dict get $DICT 12]
======
returns:
======
title {For the good times} artist {Kenny Rogers} country UK company {Mucik Master} price 8.70 year 1995
======