]> gitweb.factorcode.org Git - factor.git/blob - basis/xml/traversal/traversal.factor
factor: trim using lists
[factor.git] / basis / xml / traversal / traversal.factor
1 ! Copyright (C) 2005, 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors combinators kernel make sequences
4 sequences.deep strings xml.data ;
5 IN: xml.traversal
6
7 : children>string ( tag -- string )
8     children>> {
9         { [ dup empty? ] [ drop "" ] }
10         {
11             [ dup [ string? not ] any? ]
12             [ "XML tag unexpectedly contains non-text children" throw ]
13         }
14         [ concat ]
15     } cond ;
16
17 : deep-children>string ( tag -- string )
18     children>> [
19         [ dup tag? [ deep-children>string ] when % ] each
20     ] "" make ;
21
22 : children-tags ( tag -- sequence )
23     children>> [ tag? ] filter ;
24
25 : first-child-tag ( tag -- child )
26     children>> [ tag? ] find nip ;
27
28 : tag-named? ( name elem -- ? )
29     dup tag? [ names-match? ] [ 2drop f ] if ;
30
31 : tag-named ( tag name/string -- matching-tag )
32     assure-name '[ _ swap tag-named? ] find nip ;
33
34 : tags-named ( tag name/string -- tags-seq )
35     assure-name '[ _ swap tag-named? ] { } filter-as ;
36
37 <PRIVATE
38
39 : prepare-deep ( xml name/string -- tag name/string )
40     [ dup xml? [ body>> ] when ] [ assure-name ] bi* ;
41
42 PRIVATE>
43
44 : deep-tag-named ( tag name/string -- matching-tag )
45     prepare-deep '[ _ swap tag-named? ] deep-find ;
46
47 : deep-tags-named ( tag name/string -- tags-seq )
48     prepare-deep '[ _ swap tag-named? ] { } deep-filter-as ;
49
50 : tag-with-attr? ( elem attr-value attr-name -- ? )
51     rot dup tag? [ swap attr = ] [ 3drop f ] if ;
52
53 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
54     assure-name '[ _ _ tag-with-attr? ] find nip ;
55
56 : tag-named-with-attr ( tag tag-name attr-value attr-name -- matching-tag )
57     [ tags-named ] 2dip '[ _ _ tag-with-attr? ] find nip ;
58
59 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
60     assure-name '[ _ _ tag-with-attr? ] { } filter-as ;
61
62 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
63     assure-name '[ _ _ tag-with-attr? ] deep-find ;
64
65 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
66     assure-name '[ _ _ tag-with-attr? ] deep-filter ;
67
68 : get-id ( tag id -- elem )
69     "id" deep-tag-with-attr ;
70
71 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
72     [ deep-tags-named ] 2dip tags-with-attr ;
73
74 : assert-tag ( name name -- )
75     names-match? [ "Unexpected XML tag found" throw ] unless ;