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 xml.writer debugger
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 : children-tags ( tag -- sequence )
19 children>> [ tag? ] filter ;
21 : first-child-tag ( tag -- tag )
22 children>> [ tag? ] find nip ;
24 : tag-named? ( name elem -- ? )
25 dup tag? [ names-match? ] [ 2drop f ] if ;
27 : tag-named ( tag name/string -- matching-tag )
28 assure-name '[ _ swap tag-named? ] find nip ;
30 : tags-named ( tag name/string -- tags-seq )
31 assure-name '[ _ swap tag-named? ] filter { } like ;
35 : prepare-deep ( xml name/string -- tag name/string )
36 [ dup xml? [ body>> ] when ] [ assure-name ] bi* ;
40 : deep-tag-named ( tag name/string -- matching-tag )
41 prepare-deep '[ _ swap tag-named? ] deep-find ;
43 : deep-tags-named ( tag name/string -- tags-seq )
44 prepare-deep '[ _ swap tag-named? ] deep-filter { } like ;
46 : tag-with-attr? ( elem attr-value attr-name -- ? )
47 rot dup tag? [ swap attr = ] [ 3drop f ] if ;
49 : tag-with-attr ( tag attr-value attr-name -- matching-tag )
50 assure-name '[ _ _ tag-with-attr? ] find nip ;
52 : tags-with-attr ( tag attr-value attr-name -- tags-seq )
53 assure-name '[ _ _ tag-with-attr? ] filter children>> ;
55 : deep-tag-with-attr ( tag attr-value attr-name -- matching-tag )
56 assure-name '[ _ _ tag-with-attr? ] deep-find ;
58 : deep-tags-with-attr ( tag attr-value attr-name -- tags-seq )
59 assure-name '[ _ _ tag-with-attr? ] deep-filter ;
61 : get-id ( tag id -- elem )
62 "id" deep-tag-with-attr ;
64 : deep-tags-named-with-attr ( tag tag-name attr-value attr-name -- tags )
65 [ deep-tags-named ] 2dip tags-with-attr ;
67 : assert-tag ( name name -- )
68 names-match? [ "Unexpected XML tag found" throw ] unless ;