1 ! Copyright (C) 2005, 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel namespaces sequences words io assocs
4 quotations strings parser lexer arrays xml.data make
5 splitting vectors sequences.deep combinators fry memoize ;
8 : children>string ( tag -- string )
10 { [ dup empty? ] [ drop "" ] }
12 [ dup [ string? not ] any? ]
13 [ "XML tag unexpectedly contains non-text children" throw ]
18 : deep-children>string ( tag -- string )
20 [ dup tag? [ deep-children>string ] when % ] each
23 : children-tags ( tag -- sequence )
24 children>> [ tag? ] filter ;
26 : first-child-tag ( tag -- child )
27 children>> [ tag? ] find nip ;
29 : tag-named? ( name elem -- ? )
30 dup tag? [ names-match? ] [ 2drop f ] if ;
32 : tag-named ( tag name/string -- matching-tag )
33 assure-name '[ _ swap tag-named? ] find nip ;
35 : tags-named ( tag name/string -- tags-seq )
36 assure-name '[ _ swap tag-named? ] { } filter-as ;
40 : prepare-deep ( xml name/string -- tag name/string )
41 [ dup xml? [ body>> ] when ] [ assure-name ] bi* ;
45 : deep-tag-named ( tag name/string -- matching-tag )
46 prepare-deep '[ _ swap tag-named? ] deep-find ;
48 : deep-tags-named ( tag name/string -- tags-seq )
49 prepare-deep '[ _ swap tag-named? ] { } deep-filter-as ;
51 : tag-with-attr? ( elem attr-value attr-name -- ? )
52 rot dup tag? [ swap attr = ] [ 3drop f ] if ;
54 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
55 assure-name '[ _ _ tag-with-attr? ] find nip ;
57 : tag-named-with-attr ( tag tag-name attr-value attr-name -- matching-tag )
58 [ tags-named ] 2dip '[ _ _ tag-with-attr? ] find nip ;
60 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
61 assure-name '[ _ _ tag-with-attr? ] { } filter-as ;
63 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
64 assure-name '[ _ _ tag-with-attr? ] deep-find ;
66 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
67 assure-name '[ _ _ tag-with-attr? ] deep-filter ;
69 : get-id ( tag id -- elem )
70 "id" deep-tag-with-attr ;
72 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
73 [ deep-tags-named ] 2dip tags-with-attr ;
75 : assert-tag ( name name -- )
76 names-match? [ "Unexpected XML tag found" throw ] unless ;