01: /*
02: * MyGWT Widget Library
03: * Copyright(c) 2007, MyGWT.
04: * licensing@mygwt.net
05: *
06: * http://mygwt.net/license
07: */
08: package net.mygwt.ui.client.data;
09:
10: import java.util.HashMap;
11: import java.util.Map;
12:
13: import com.google.gwt.xml.client.Document;
14: import com.google.gwt.xml.client.Element;
15: import com.google.gwt.xml.client.Node;
16: import com.google.gwt.xml.client.NodeList;
17: import com.google.gwt.xml.client.XMLParser;
18:
19: /**
20: * A <code>DataReader</code> implementation that reads XML data using a
21: * <code>ModelType</code> definition and creates <code>Model</code>
22: * instances.
23: */
24: public class XMLReader implements DataReader {
25:
26: private ModelType modelType;
27:
28: public XMLReader(ModelType modelType) {
29: this .modelType = modelType;
30: }
31:
32: public LoadResult read(Object data) {
33: Document doc = XMLParser.parse((String) data);
34: Node root = doc.getFirstChild();
35: NodeList list = doc.getElementsByTagName(modelType.recordName);
36: DataList records = new DataList();
37: for (int i = 0; i < list.getLength(); i++) {
38: Node node = list.item(i);
39: Element elem = (Element) node;
40: Map values = new HashMap();
41: for (int j = 0; j < modelType.getFieldCount(); j++) {
42: DataField field = modelType.getField(j);
43: String map = field.map != null ? field.map : field.name;
44: String v = getValue(elem, map);
45: values.put(field.name, v);
46: }
47: records.add(new Model(values));
48: }
49:
50: int totalCount = records.size();
51:
52: if (modelType.totalName != null) {
53: Node totalNode = root.getAttributes().getNamedItem(
54: modelType.totalName);
55: if (totalNode != null) {
56: String sTot = totalNode.getNodeValue();
57: totalCount = Integer.parseInt(sTot);
58: }
59: }
60:
61: LoadResult result = new LoadResult(records);
62: result.totalLength = totalCount;
63: return result;
64: }
65:
66: protected String getValue(Element elem, String name) {
67: if (elem.hasAttribute(name)) {
68: return elem.getAttribute(name);
69: } else {
70: NodeList elems = elem.getElementsByTagName(name);
71: if (elems != null) {
72: elem = (Element) elems.item(0);
73: if (elem != null && elem.getFirstChild() != null) {
74: return elem.getFirstChild().getNodeValue();
75: }
76: }
77: return "";
78: }
79: }
80:
81: }
|