File: xml.tcl

package info (click to toggle)
libapache2-mod-rivet 3.2.0-1
  • links: PTS
  • area: main
  • in suites: bullseye
  • size: 5,868 kB
  • sloc: xml: 8,496; tcl: 7,212; ansic: 6,959; sh: 5,030; makefile: 261; sql: 91; lisp: 78
file content (104 lines) | stat: -rw-r--r-- 2,335 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#
# xml.tcl --
#
# Syntax:
#
#       ::rivet::xml string ?tag ?attr val? ?attr val?? ?tag ?attr val? ?attr val??
#
# or
#
#       ::rivet::xml ?tag ?attr val? ?attr val??
#
# Example 1:
#
# trivial nested markup fragment
#
#  ::rivet::xml Test b i 
# <= <b><i>Test</i></b>
#  
# Example 2:
#
# XHTML Element with attributes
#
# ::rivet::xml Test [list div class box id testbox] b i
# <= <div class="box" id="testbox"><b><i>Test</i></b></div>
#
# Example 3
#
# ::rivet::xml "anything ..." div [list a href "http://..../" title "info message"] 
# <= <div><a href="http://..../" title="info message">anything ...</a></div>
#
# Example 4
#
# ::rivet::xml "" [list a attr1 val1 attr2 val2] [list b attr1 val1 attr2 val2]
# <= <a attr1="val1" attr2="val2"><b attr1="val1" attr2="val2"></b></a>
#
# Example 5
#
# single self closing element
#
# ::rivet::xml [list a attr1 val1 attr2 val2]
# <= <a attr1="val1" attr2="val2" />
#

namespace eval ::rivet {

    proc xml {textstring args} {

        set single_element [::rivet::lempty $args]
        if {$single_element} {

            set tags_list   [list $textstring]

            if {[::rivet::lempty $tags_list]} { return "" }

        } else {

            set tags_list $args

        }

        set tags_stack  {}
        set el          {}
        set xmlout      ""
        foreach el $tags_list {

            set el  [lassign $el tag]
            lappend tags_stack $tag
            append  xmlout "<$tag"

            foreach {attrib attrib_v} $el {
                append xmlout " $attrib=\"$attrib_v\""
            }

            append xmlout ">"
        }


        if {[::rivet::lempty $tags_stack]} {

            return $textstring

        } elseif {$single_element} {

            # variable 'el' keeps the last (innermost) attribute-value list

            if {[::rivet::lempty $el] == 1} {
                set xmlout [string replace $xmlout end end " />"]
            } else {
                set xmlout [string replace $xmlout end end "/>"]
            }

            if {[llength $tags_stack] > 1} {
                set xmlout [append xmlout "</[join [lreverse [lrange $tags_stack 0 end-1]] "></"]>"]
            }
            return $xmlout

        } else {

            return [append xmlout "$textstring</[join [lreverse $tags_stack] "></"]>"]

        }
    }

}