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 ;
7 : children>string ( tag -- string )
9 { [ dup empty? ] [ drop "" ] }
11 [ dup [ string? not ] any? ]
12 [ "XML tag unexpectedly contains non-text children" throw ]
17 : deep-children>string ( tag -- string )
19 [ dup tag? [ deep-children>string ] when % ] each
22 : children-tags ( tag -- sequence )
23 children>> [ tag? ] filter ;
25 : first-child-tag ( tag -- child )
26 children>> [ tag? ] find nip ;
28 : tag-named? ( name elem -- ? )
29 dup tag? [ names-match? ] [ 2drop f ] if ;
31 : tag-named ( tag name/string -- matching-tag )
32 assure-name '[ _ swap tag-named? ] find nip ;
34 : tags-named ( tag name/string -- tags-seq )
35 assure-name '[ _ swap tag-named? ] { } filter-as ;
39 : prepare-deep ( xml name/string -- tag name/string )
40 [ dup xml? [ body>> ] when ] [ assure-name ] bi* ;
44 : deep-tag-named ( tag name/string -- matching-tag )
45 prepare-deep '[ _ swap tag-named? ] deep-find ;
47 : deep-tags-named ( tag name/string -- tags-seq )
48 prepare-deep '[ _ swap tag-named? ] { } deep-filter-as ;
50 : tag-with-attr? ( elem attr-value attr-name -- ? )
51 rot dup tag? [ swap attr = ] [ 3drop f ] if ;
53 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
54 assure-name '[ _ _ tag-with-attr? ] find nip ;
56 : tag-named-with-attr ( tag tag-name attr-value attr-name -- matching-tag )
57 [ tags-named ] 2dip '[ _ _ tag-with-attr? ] find nip ;
59 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
60 assure-name '[ _ _ tag-with-attr? ] { } filter-as ;
62 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
63 assure-name '[ _ _ tag-with-attr? ] deep-find ;
65 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
66 assure-name '[ _ _ tag-with-attr? ] deep-filter ;
68 : get-id ( tag id -- elem )
69 "id" deep-tag-with-attr ;
71 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
72 [ deep-tags-named ] 2dip tags-with-attr ;
74 : assert-tag ( name name -- )
75 names-match? [ "Unexpected XML tag found" throw ] unless ;