dom: return a more precise `Array[XMLTag]` as the doc already said
[nit.git] / lib / dom / dom.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Easy XML DOM parser
12 module dom
13
14 import parser
15
16 redef class XMLEntity
17
18 # The `XMLTag` children with the `tag_name`
19 #
20 # ~~~
21 # var code = """
22 # <?xml version="1.0" encoding="us-ascii"?>
23 # <animal>
24 # <cat/>
25 # <tiger>This is a white tiger!</tiger>
26 # <cat/>
27 # </animal>"""
28 #
29 # var xml = code.to_xml
30 # assert xml["animal"].length == 1
31 # assert xml["animal"].first["cat"].length == 2
32 # ~~~
33 fun [](tag_name: String): Array[XMLTag]
34 do
35 var res = new Array[XMLTag]
36 for child in children do
37 if child isa XMLTag and child.tag_name == tag_name then
38 res.add child
39 end
40 end
41 return res
42 end
43 end
44
45 redef class XMLStartTag
46
47 # Content of this XML tag held within a `PCDATA` or `CDATA`
48 #
49 # ~~~
50 # var code = """
51 # <?xml version="1.0" encoding="us-ascii"?>
52 # <animal>
53 # <cat/>
54 # <tiger>This is a white tiger!</tiger>
55 # <cat/>
56 # </animal>"""
57 #
58 # var xml = code.to_xml
59 # assert xml["animal"].first["tiger"].first.as(XMLStartTag).data == "This is a white tiger!"
60 # ~~~
61 fun data: String
62 do
63 for child in children do
64 if child isa PCDATA then return child.content
65 if child isa CDATA then return child.content
66 end
67 abort
68 end
69 end