Statistics
| Revision:

root / trunk / applications / appCatalogYNomenclatorClient / src / es / gva / cit / catalogClient / metadataXML / XMLNode.java @ 3073

History | View | Annotate | Download (7.59 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
*
3
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
*
5
* This program is free software; you can redistribute it and/or
6
* modify it under the terms of the GNU General Public License
7
* as published by the Free Software Foundation; either version 2
8
* of the License, or (at your option) any later version.
9
*
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
* GNU General Public License for more details.
14
*
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
*
19
* For more information, contact:
20
*
21
*  Generalitat Valenciana
22
*   Conselleria d'Infraestructures i Transport
23
*   Av. Blasco Ib??ez, 50
24
*   46010 VALENCIA
25
*   SPAIN
26
*
27
*      +34 963862235
28
*   gvsig@gva.es
29
*      www.gvsig.gva.es
30
*
31
*    or
32
*
33
*   IVER T.I. S.A
34
*   Salamanca 50
35
*   46005 Valencia
36
*   Spain
37
*
38
*   +34 963163400
39
*   dac@iver.es
40
*/
41
package es.gva.cit.catalogClient.metadataXML;
42

    
43
import java.io.File;
44
import java.io.FileWriter;
45
import java.io.InputStream;
46
import java.io.Writer;
47
import java.util.Hashtable;
48
import java.util.Vector;
49

    
50
import javax.xml.parsers.DocumentBuilderFactory;
51

    
52
import org.w3c.dom.Document;
53
import org.w3c.dom.Element;
54
import org.w3c.dom.NamedNodeMap;
55
import org.w3c.dom.Node;
56
import org.w3c.dom.NodeList;
57

    
58
/**
59
 * Esta clase representa un XMLNode simplificado
60
 * Contiene una lista de subnodos y una lista de atributos.
61
 * Tambi?n tiene una cadena.
62
 * 
63
 * Soporta la lectura y escritura de y desde un fichero XML.
64
 * Tambi?n soporta la lectura desde Internet
65
 *
66
 * Modificado por jaume
67
 */ 
68

    
69
public class XMLNode {
70
   
71
   // subnodos
72
   private Vector subNodes = new Vector();
73
   // atributos
74
   private Hashtable attr = new Hashtable();
75
   private String nodeName;
76
   private String text = null;
77
   // los nombres de los atributos
78
   private Vector attrKeys = new Vector();
79
   // cabecera XML
80
   private String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
81

    
82
   /**
83
    * Constructor, lee de un fichero
84
    * 
85
    * @author jaume - jaume.dominguez@iver.es
86
    * Modified by Jorge Piera Llodra - piera_jor@gva.es
87
    */ 
88
   public XMLNode(File file) throws Exception {
89
      this(factory.newDocumentBuilder().parse(file));
90
   }
91
   
92
   /**
93
    * Constructor. Usando url.openStream() se puede usar
94
    * para leer info descargada de internet.
95
    * @param inputstream
96
    * @throws Exception
97
    */
98
   public XMLNode(InputStream inputstream) throws Exception{
99
      this(factory.newDocumentBuilder().parse(inputstream));
100
   }
101

    
102
   /**
103
    * Contructor, constructor desde un documento DOM
104
    * 
105
    * @author jaume - jaume.dominguez@iver.es
106
    *
107
    */ 
108
   public XMLNode(Document dom) throws Exception {
109
      this((Element)dom.getFirstChild());
110
   }
111

    
112
   /**
113
    *  Contructor, crea un nodo con su nombre
114
    */
115
   public XMLNode(String name) throws Exception {
116
      nodeName = name;
117
   }
118

    
119
   /**
120
    * Contructor, crea un nodo con su nombre y el texto
121
    */ 
122
   public XMLNode(String name, String text) throws Exception {
123
      nodeName = name;
124
      this.text = text;
125
   }
126

    
127
   /**
128
    * Contructor, desde un elemento DOM
129
    */
130
   public XMLNode(Element dom) throws Exception {
131
      nodeName = dom.getNodeName();
132
      NamedNodeMap map = dom.getAttributes();
133
      for (int i = 0; i < map.getLength(); i++) {
134
         Node att = map.item(i);
135
         addAtrribute(att.getNodeName(), att.getNodeValue());
136
      }
137
      NodeList nodeList = dom.getChildNodes();
138
      for (int i = 0; i < nodeList.getLength(); i++) {
139
         Node sub = nodeList.item(i);
140
         if (sub.getNodeType() == Node.ELEMENT_NODE) {
141
            addSubNode(new XMLNode((Element)sub));
142
         }
143
         else if (sub.getNodeType() == Node.TEXT_NODE) {
144
            String s = sub.getNodeValue().trim();
145
            if (s.length() > 0) {
146
               if (text != null) {
147
                  throw new Exception("XMLNode '" + nodeName + "' has 2 Textblocks");
148
               }
149
               text = s;
150
            }
151
         }
152
      }
153
   }
154

    
155
   public void setText(String s) {
156
      text = s;
157
   }
158

    
159
   public void addSubNode(XMLNode s) {
160
      subNodes.add(s);
161
   }
162

    
163
   public void addAtrribute(String name, String value) throws Exception {
164
      if (attr.containsKey(name)) {
165
         throw new Exception(
166
               "XMLNode '" + nodeName + "' already contains Attribute '" + name + "'");
167
      }
168
      attr.put(name, value);
169
      attrKeys.add(name);
170
   }
171

    
172
   public int getNumSubNodes() {
173
      return subNodes.size();
174
   }
175

    
176
   public String getName() {
177
      return nodeName;
178
   }
179

    
180
   public String getText() {
181
      return text;
182
   }
183

    
184
   public XMLNode getSubNode(int index) {
185
      return (XMLNode)subNodes.get(index);
186
   }
187
   
188
   public XMLNode[] getSubnodes(){
189
       XMLNode[] xmlNodes = new XMLNode[getNumSubNodes()];
190
       for (int i=0 ; i<getNumSubNodes() ; i++){
191
           xmlNodes[i] = getSubNode(i);
192
       }
193
       return xmlNodes;
194
   }
195

    
196
   public Vector getAttributeNames() {
197
       return attrKeys;
198
   }
199
   
200
   public void write(Writer wr) throws Exception {
201
      wwrite("", wr);
202
   }
203

    
204
   /**
205
    * Escribe el c?digo XML de este objeto con su identaci?n
206
    */ 
207
   private void wwrite(String pre, Writer wr) throws Exception {
208
      wr.write(pre + "<" + nodeName);
209
      for (int i = 0; i < attrKeys.size(); i++) {
210
         String name = (String)attrKeys.get(i);
211
         String val = (String)attr.get(name);
212
         wr.write(" " + name + "='" + val + "'");
213
      }
214
      if (getNumSubNodes() == 0 && text == null) {
215
         wr.write("/>\n");
216
      }
217
      else {
218
         wr.write(">");
219
         if (text != null) {
220
            wr.write(text);
221
         }
222
         if (getNumSubNodes() > 0) {
223
            wr.write("\n");
224
            for (int i = 0; i < subNodes.size(); i++) {
225
               if (getSubNode(i) != null) {
226
                  getSubNode(i).wwrite(pre + "  ", wr);
227
               }
228
            }
229
            wr.write(pre + "</" + nodeName + ">\n");
230
         }
231
         else {
232
            wr.write("</" + nodeName + ">\n");
233
         }
234
      }
235
   }
236
   
237
   public String getAttribute(String key) {
238
      return (String)attr.get(key);
239
   }
240

    
241
   public double getDoubleAttribute(String key) {
242
      return Double.parseDouble((String)attr.get(key));
243
   }
244

    
245
   public boolean getBoolAttribute(String key) {
246
      if (!hasAttribute(key)) {
247
         return false;
248
      }
249
      return new Boolean((String)attr.get(key)).booleanValue();
250
   }
251

    
252
   public int getIntAttribute(String key) {
253
      return Integer.parseInt((String)attr.get(key));
254
   }
255

    
256
   public boolean hasAttribute(String key) {
257
      return attr.containsKey(key);
258
   }
259

    
260
   // escribe al fichero
261
   public void write(File f) throws Exception {
262
      FileWriter fw = new FileWriter(f);
263
      fw.write(header);
264
      write(fw);
265
      fw.flush();
266
      fw.close();
267
   }
268

    
269

    
270
   public String toString() {
271
      return this.getName();
272
      /*
273
       StringWriter wr = new StringWriter();
274
      try {
275
         write(wr);
276
      }
277
      catch (Exception e) {
278
         System.err.println("Exception in StringWriter " + e);
279
         e.printStackTrace();
280
         System.exit(1);
281
      }
282
      return wr.toString();
283
      */
284
   }
285

    
286
   static DocumentBuilderFactory factory;
287
   static {
288
      factory = DocumentBuilderFactory.newInstance();
289
      factory.setValidating(false);
290
      factory.setNamespaceAware(false);
291
      factory.setIgnoringComments(true);
292
   }
293

    
294
   public void setHeader(String header) {
295
      this.header = header;
296
   }
297

    
298
 
299
}