1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package groovy.util.slurpersupport;
18
19 import groovy.lang.Closure;
20 import groovy.lang.GroovyObject;
21 import groovy.lang.GroovyRuntimeException;
22
23 import java.io.IOException;
24 import java.io.Writer;
25 import java.util.Map;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.ArrayList;
29
30 /***
31 * @author John Wilson
32 */
33
34 class Attributes extends NodeChildren {
35 final String attributeName;
36
37 public Attributes(final GPathResult parent, final String name, final String namespacePrefix, final Map namespaceTagHints) {
38 super(parent, name, namespacePrefix, namespaceTagHints);
39 this.attributeName = this.name.substring(1);
40 }
41
42 public Attributes(final GPathResult parent, final String name, final Map namespaceTagHints) {
43 this(parent, name, "*", namespaceTagHints);
44 }
45
46 public String name() {
47
48 return this.name.substring(1);
49 }
50
51 public Iterator childNodes() {
52 throw new GroovyRuntimeException("Can't get the child nodes on a a GPath expression selecting attributes: ...." + this.parent.name() + "." + name() + ".childNodes()");
53 }
54
55 public Iterator iterator() {
56 return new NodeIterator(nodeIterator()) {
57 protected Object getNextNode(final Iterator iter) {
58 while (iter.hasNext()) {
59 final Object next = iter.next();
60 if (next instanceof Attribute) {
61 return next;
62 } else {
63 final String value = (String) ((Node) next).attributes().get(Attributes.this.attributeName);
64 if (value != null) {
65 return new Attribute(Attributes.this.attributeName,
66 value,
67 new NodeChild((Node) next, Attributes.this.parent.parent, "", Attributes.this.namespaceTagHints),
68 "",
69 Attributes.this.namespaceTagHints);
70 }
71 }
72 }
73 return null;
74 }
75 };
76 }
77
78 public Iterator nodeIterator() {
79 return this.parent.nodeIterator();
80 }
81
82 public GPathResult parents() {
83 return super.parents();
84 }
85
86 public String text() {
87 final StringBuffer buf = new StringBuffer();
88 final Iterator iter = iterator();
89 while (iter.hasNext()) {
90 buf.append(iter.next());
91 }
92 return buf.toString();
93 }
94
95 public List list() {
96 final Iterator iter = iterator();
97 final List result = new ArrayList();
98 while (iter.hasNext()) {
99 result.add(iter.next());
100 }
101 return result;
102 }
103
104 public GPathResult findAll(final Closure closure) {
105 return new FilteredAttributes(this, closure, this.namespaceTagHints);
106 }
107
108 public Writer writeTo(final Writer out) throws IOException {
109 out.write(text());
110 return out;
111 }
112
113 public void build(final GroovyObject builder) {
114 builder.getProperty("mkp");
115 builder.invokeMethod("yield", new Object[]{text()});
116 }
117 }