This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

looking for xml2dict

Help for those learning Tcl or writing their own scripts.
Post Reply
User avatar
CrazyCat
Revered One
Posts: 1334
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

looking for xml2dict

Post by CrazyCat »

Hello there,

I'm currently working on a tcl which use an XML as datasource.
I've found an usefull procedure:

Code: Select all

proc xml2list xml {
     regsub -all {>\s*<} [string trim $xml " \n\t<>"] "\} \{" xml
     set xml [string map {> "\} \{#text \{" < "\}\} \{"}  $xml]

     set res ""   ;# string to collect the result
     set stack {} ;# track open tags
     set rest {}
     foreach item "{$xml}" {
	 switch -regexp -- $item {
	    ^# {append res "{[lrange $item 0 end]} " ; #text item}
	    ^/ {
		regexp {/(.+)} $item -> tagname ;# end tag
		set expected [lindex $stack end]
		if {$tagname!=$expected} {error "$item != $expected"}
		set stack [lrange $stack 0 end-1]
		append res "\}\} "
	  }
	    /$ { # singleton - start and end in one <> group
	       regexp {([^ ]+)( (.+))?/$} $item -> tagname - rest
	       set rest [lrange [string map {= " "} $rest] 0 end]
	       append res "{$tagname [list $rest] {}} "
	    }
	    default {
	       set tagname [lindex $item 0] ;# start tag
	       set rest [lrange [string map {= " "} $item] 1 end]
	       lappend stack $tagname
	       append res "\{$tagname [list $rest] \{"
	    }
	 }
	 if {[llength $rest]%2} {error "att's not paired: $rest"}
     }
     if [llength $stack] {error "unresolved: $stack"}
     string map {"\} \}" "\}\}"} [lindex $res 0]
 }
Put I prefer working with dict than with list, so does anyone has an xml2dict procedure ?
I think I can do it, but I'm quite lazy :)

Thanks by advance
Post Reply