KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dom > DOMDocument


1 package dom;
2
3 import java.lang.ClassNotFoundException JavaDoc;
4 import java.lang.IllegalAccessException JavaDoc;
5
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.OutputStream JavaDoc;
9 import java.io.OutputStreamWriter JavaDoc;
10 import java.io.PrintWriter JavaDoc;
11 import java.io.StringBufferInputStream JavaDoc;
12 import java.io.StringWriter JavaDoc;
13 import java.io.UnsupportedEncodingException JavaDoc;
14 import java.io.UTFDataFormatException JavaDoc;
15 import java.io.Writer JavaDoc;
16 import java.io.File JavaDoc;
17 import java.io.FileInputStream JavaDoc;
18 import java.io.FileNotFoundException JavaDoc;
19 import java.io.Reader JavaDoc;
20 import java.io.FileReader JavaDoc;
21 import java.io.InputStreamReader JavaDoc;
22 import java.io.UnsupportedEncodingException JavaDoc;
23
24 import java.util.Vector JavaDoc;
25
26 import org.w3c.dom.*;
27 import org.xml.sax.InputSource JavaDoc;
28 import org.xml.sax.SAXNotRecognizedException JavaDoc;
29 import org.xml.sax.SAXNotSupportedException JavaDoc;
30 import org.xml.sax.SAXException JavaDoc;
31
32 import com.knowgate.dfs.FileSystem;
33 import com.knowgate.debug.DebugFile;
34
35 public class DOMDocument {
36
37     //---------------------------------------------------------
38
// Private Member Variables
39

40     private String JavaDoc sEncoding;
41     private boolean bCanonical;
42     private boolean bValidation;
43     private boolean bNamespaces;
44     private Writer oPrtWritter;
45     private Document oDocument;
46
47     //---------------------------------------------------------
48
// Constructors
49

50     /**
51      * <p>Create new DOMDocument</p>
52      * Default properties:<br>
53      * canonical = <b>false</b>
54      * validation = <b>false</b>
55      * namespaces = <b>true</b>
56      * enconding = ISO-8859-1
57      */

58     public DOMDocument() {
59       if (DebugFile.trace) DebugFile.writeln("new DOMDocument()");
60
61       bCanonical = false;
62       bValidation = false;
63       bNamespaces = true;
64       sEncoding = "UTF-8";
65     } // DOMDocument()
66

67     /**
68      * <p>Create new DOMDocument</p>
69      * @param sEncodingType Encoding {ISO-8859-1, UTF-8, UTF-16, ASCII-7, ...}
70      * @param bValidateXML Activate/Deactivate schema-validation
71      * @param bCanonicalXML Activate/Deactivate Canonical XML
72      */

73     public DOMDocument(String JavaDoc sEncodingType, boolean bValidateXML, boolean bCanonicalXML) {
74       if (DebugFile.trace) DebugFile.writeln("new DOMDocument(" + sEncodingType + "," + String.valueOf(bValidateXML) + "," + String.valueOf(bCanonicalXML) + ")");
75
76       bCanonical = bCanonicalXML;
77       bValidation = bValidateXML;
78       bNamespaces = true;
79       sEncoding = sEncodingType;
80     } // DOMDocument()
81

82     /**
83      * <p>Create a DOMDocument from an XML Document</p>
84      * @param oW3CDoc org.w3c.dom.Document
85      */

86     public DOMDocument(Document oW3CDoc) {
87       if (DebugFile.trace) DebugFile.writeln("new DOMDocument([Document])");
88
89       bCanonical = false;
90       bValidation = false;
91       bNamespaces = true;
92       sEncoding = "UTF-8";
93       oDocument = oW3CDoc;
94     } // DOMDocument()
95

96     //---------------------------------------------------------
97
// Methods
98

99     public Document getDocument() {
100       return oDocument;
101     } // getDocument()
102

103     //---------------------------------------------------------
104

105     public Node getRootNode() {
106       return oDocument;
107     } // getRootNode()
108

109     //---------------------------------------------------------
110

111     public Element getRootElement() {
112       return oDocument.getDocumentElement();
113     } // getRootElement()
114

115     //---------------------------------------------------------
116

117     public String JavaDoc getAttribute(Node oNode, String JavaDoc sAttrName) {
118       NamedNodeMap oMap = oNode.getAttributes();
119       Node oItem = oMap.getNamedItem(sAttrName);
120
121       if (null==oItem)
122         return null;
123       else
124         return oItem.getNodeValue();
125     } // getAttribute()
126

127     //---------------------------------------------------------
128

129     public void setAttribute(Node oNode, String JavaDoc sAttrName, String JavaDoc sAttrValue) {
130       Attr oAttr = oDocument.createAttribute(sAttrName);
131       oAttr.setNodeValue(sAttrValue);
132       ((Element) oNode).setAttributeNode(oAttr);
133     } // setAttribute()
134

135
136     //---------------------------------------------------------
137

138     public boolean getValidation() {
139       return bValidation;
140     }
141
142     //---------------------------------------------------------
143

144     public void setValidation(boolean bValidate) {
145       bValidation = bValidate;
146     }
147
148     //---------------------------------------------------------
149

150     public boolean getNamesSpaces() {
151       return bNamespaces;
152     }
153
154     //---------------------------------------------------------
155

156     public void setNamesSpaces(boolean bNames) {
157       bNamespaces = bNames;
158     }
159
160     //---------------------------------------------------------
161

162     public String JavaDoc getWriterEncoding() {
163       return sEncoding;
164     } // getWriterEncoding()
165

166     // ----------------------------------------------------------
167

168     public String JavaDoc getTextValue(Element oElement) {
169       return oElement.getFirstChild().getNodeValue();
170     } // getTextValue()
171

172     // ----------------------------------------------------------
173

174     public Element getFirstElement(Node oParent) {
175       Node oCurrentNode = null;
176
177       for (oCurrentNode=oParent.getFirstChild(); oCurrentNode!=null; oCurrentNode=oCurrentNode.getNextSibling())
178         if (Node.ELEMENT_NODE==oCurrentNode.getNodeType())
179           break;
180
181       return (Element) oCurrentNode;
182     } // getFirstElement()
183

184     // ----------------------------------------------------------
185

186     public Element getNextElement(Node oPreviousSibling) {
187       Node oCurrentNode = null;
188
189       for (oCurrentNode=oPreviousSibling.getNextSibling(); oCurrentNode!=null; oCurrentNode=oCurrentNode.getNextSibling())
190         if (Node.ELEMENT_NODE==oCurrentNode.getNodeType())
191           break;
192
193       return (Element) oCurrentNode;
194     } // getNextElement()
195

196     // ----------------------------------------------------------
197

198     public Element seekChildByName(Node oParent, String JavaDoc sName) {
199       // Busca el nodo hijo que tenga un nombre dado
200
Node oCurrentNode = null;
201       String JavaDoc sCurrentName;
202
203       for (oCurrentNode=getFirstElement(oParent); oCurrentNode!=null; oCurrentNode=getNextElement(oCurrentNode)) {
204         sCurrentName = oCurrentNode.getNodeName();
205         if (sName.equals(sCurrentName))
206           break;
207       } // next(oCurrentNode)
208

209       return (Element) oCurrentNode;
210     } // seekChildByName()
211

212     // ----------------------------------------------------------
213

214     public Element seekChildByAttr(Node oParent, String JavaDoc sAttrName, String JavaDoc sAttrValue) {
215       // Busca el nodo hijo que tenga un atributo con un valor determinado
216
Node oCurrentNode = null;
217
218       for (oCurrentNode=getFirstElement(oParent); oCurrentNode!=null; oCurrentNode=getNextElement(oCurrentNode)) {
219         if (getAttribute(oCurrentNode, sAttrName).equals(sAttrValue));
220           break;
221       } // next(iNode)
222

223       return (Element) oCurrentNode;
224     } // seekChildByName()
225

226     //---------------------------------------------------------
227

228     public void parseURI(String JavaDoc sURI, String JavaDoc sEncoding)
229       throws ClassNotFoundException JavaDoc, UTFDataFormatException JavaDoc,
230              IllegalAccessException JavaDoc, InstantiationException JavaDoc,
231              FileNotFoundException JavaDoc, UnsupportedEncodingException JavaDoc, IOException JavaDoc,
232              SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc, Exception JavaDoc {
233
234       Class JavaDoc oXerces;
235       Reader JavaDoc oReader;
236       DOMParserWrapper oParserWrapper;
237
238       if (DebugFile.trace) {
239         DebugFile.writeln("Begin DOMDocument.parseURI(" + sURI + "," + sEncoding + ")");
240         DebugFile.incIdent();
241         DebugFile.writeln("Class.forName(dom.wrappers.Xerces).newInstance()");
242       }
243
244       oXerces = Class.forName("dom.wrappers.Xerces");
245
246       if (null==oXerces)
247         throw new ClassNotFoundException JavaDoc("dom.wrappers.Xerces");
248
249       oParserWrapper = (DOMParserWrapper) oXerces.newInstance();
250
251       if (DebugFile.trace) {
252         DebugFile.writeln("validation=" + String.valueOf(bValidation));
253         DebugFile.writeln("namesapces=" + String.valueOf(bNamespaces));
254       }
255
256       oParserWrapper.setFeature("http://xml.org/sax/features/namespaces", bNamespaces);
257
258       // Validación XML-Schema
259
oParserWrapper.setFeature("http://xml.org/sax/features/validation", bValidation);
260       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema", bValidation);
261       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema-full-checking", bValidation);
262
263       if (sURI.startsWith("file://")) {
264         File JavaDoc oXMLFile = new File JavaDoc(sURI.substring(7));
265         if (!oXMLFile.exists()) throw new FileNotFoundException JavaDoc("DOMDocument.parseURI(" + sURI.substring(7) + ") file not found");
266         if (null==sEncoding) {
267           if (DebugFile.trace) DebugFile.writeln("new FileReader(" + sURI.substring(7) + ")");
268           oReader = new FileReader JavaDoc(oXMLFile);
269           if (DebugFile.trace) DebugFile.writeln("DOMParserWrapper.parse([InputSource])");
270         } else {
271           oReader = new InputStreamReader JavaDoc(new FileInputStream JavaDoc(oXMLFile), sEncoding);
272         }
273         oDocument = oParserWrapper.parse(new InputSource JavaDoc(oReader));
274         oReader.close();
275       }
276       else {
277         if (DebugFile.trace) DebugFile.writeln("DOMParserWrapper.parse(" + sURI + ")");
278         oDocument = oParserWrapper.parse(sURI);
279       }
280
281       if (DebugFile.trace) {
282         DebugFile.decIdent();
283         DebugFile.writeln("End DOMDocument.parseURI()");
284       }
285
286     } // parseURI()
287

288     //---------------------------------------------------------
289

290     public void parseURI(String JavaDoc sURI)
291       throws ClassNotFoundException JavaDoc, UTFDataFormatException JavaDoc,
292              FileNotFoundException JavaDoc, IllegalAccessException JavaDoc,
293              InstantiationException JavaDoc, IOException JavaDoc, Exception JavaDoc,
294              SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc {
295       parseURI(sURI,null);
296     }
297
298     //---------------------------------------------------------
299

300     public void parseStream(InputStream JavaDoc oStrm)
301       throws ClassNotFoundException JavaDoc, IllegalAccessException JavaDoc, UTFDataFormatException JavaDoc,
302       InstantiationException JavaDoc, SAXNotSupportedException JavaDoc, SAXNotRecognizedException JavaDoc,
303       Exception JavaDoc {
304
305       Class JavaDoc oXerces;
306       DOMParserWrapper oParserWrapper;
307
308       if (DebugFile.trace) {
309         DebugFile.writeln("Begin DOMDocument.parseStream()");
310         DebugFile.incIdent();
311         DebugFile.writeln("Class.forName(dom.wrappers.Xerces).newInstance()");
312       }
313
314       oXerces = Class.forName("dom.wrappers.Xerces");
315
316       if (null==oXerces)
317         throw new ClassNotFoundException JavaDoc("dom.wrappers.Xerces");
318
319       oParserWrapper = (DOMParserWrapper) oXerces.newInstance();
320
321       if (DebugFile.trace) {
322         DebugFile.writeln("validation=" + String.valueOf(bValidation));
323         DebugFile.writeln("namesapces=" + String.valueOf(bNamespaces));
324       }
325
326       oParserWrapper.setFeature("http://xml.org/sax/features/namespaces", bNamespaces);
327
328       // Validación XML-Schema
329
oParserWrapper.setFeature("http://xml.org/sax/features/validation", bValidation);
330       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema", bValidation);
331       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema-full-checking", bValidation);
332
333       if (DebugFile.trace) DebugFile.writeln("DOMParserWrapper.parse([InputSource])");
334
335       oDocument = oParserWrapper.parse(new InputSource JavaDoc(oStrm));
336
337       if (DebugFile.trace) {
338         DebugFile.decIdent();
339         DebugFile.writeln("End DOMDocument.parseStream()");
340       }
341
342     } // parseStream()
343

344     //---------------------------------------------------------
345

346 /*
347     public void parseString(String sXML)
348       throws ClassNotFoundException, IllegalAccessException, UTFDataFormatException, Exception {
349
350       Class oXerces;
351       DOMParserWrapper oParserWrapper;
352
353       if (DebugFile.trace) {
354         DebugFile.writeln("Begin DOMDocument.parseString(" + sXML + ")");
355         DebugFile.incIdent();
356         DebugFile.writeln("Class.forName(dom.wrappers.Xerces).newInstance()");
357       }
358
359       oXerces = Class.forName("dom.wrappers.Xerces");
360
361       if (null==oXerces)
362         throw new ClassNotFoundException("dom.wrappers.Xerces");
363
364       oParserWrapper = (DOMParserWrapper) oXerces.newInstance();
365
366       if (DebugFile.trace) {
367         DebugFile.writeln("validation=" + String.valueOf(bValidation));
368         DebugFile.writeln("namesapces=" + String.valueOf(bNamespaces));
369       }
370
371       oParserWrapper.setFeature("http://xml.org/sax/features/namespaces", bNamespaces);
372
373       // Validación XML-Schema
374       oParserWrapper.setFeature("http://xml.org/sax/features/validation", bValidation);
375       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema", bValidation);
376       oParserWrapper.setFeature("http://apache.org/xml/features/validation/schema-full-checking", bValidation);
377
378       if (DebugFile.trace) DebugFile.writeln("new StringBufferInputStream(\n" + sXML + "\n)");
379
380       StringBufferInputStream oStrStream = new StringBufferInputStream(sXML);
381       InputSource oInputSrc = new InputSource(oStrStream);
382
383       if (DebugFile.trace) DebugFile.writeln("DOMParserWrapper.parse([InputSource])");
384
385       oDocument = oParserWrapper.parse(oInputSrc);
386
387       oInputSrc = null;
388       oStrStream.close();
389       oStrStream = null;
390
391       if (DebugFile.trace) {
392         DebugFile.decIdent();
393         DebugFile.writeln("End DOMDocument.parseString()");
394       }
395     } // parseString()
396 */

397
398     //---------------------------------------------------------
399

400     public void print(OutputStream JavaDoc oOutStream) throws IOException JavaDoc,UnsupportedEncodingException JavaDoc {
401       oPrtWritter = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(oOutStream, sEncoding));
402       print(oDocument);
403     } // print()
404

405     //---------------------------------------------------------
406

407     public String JavaDoc print() throws IOException JavaDoc,UnsupportedEncodingException JavaDoc {
408       oPrtWritter = new StringWriter JavaDoc();
409       print(oDocument);
410       return oPrtWritter.toString();
411     } // print()
412

413     //---------------------------------------------------------
414

415     private void print(Node node) throws IOException JavaDoc {
416         // is there anything to do?
417
if ( node == null ) {
418             return;
419         }
420
421         int type = node.getNodeType();
422         switch ( type ) {
423         // print document
424
case Node.DOCUMENT_NODE: {
425                 if ( !bCanonical ) {
426                     String JavaDoc Encoding = this.getWriterEncoding();
427                     if ( Encoding.equalsIgnoreCase( "DEFAULT" ) )
428                         Encoding = "ISO-8859-1";
429                     else if ( Encoding.equalsIgnoreCase( "Unicode" ) )
430                         Encoding = "UTF-16";
431                     else
432                         //Encoding = MIME2Java.reverse( Encoding );
433
Encoding = "ISO-8859-1";
434
435                     oPrtWritter.write("<?xml version=\"1.0\" encoding=\""+
436                                 Encoding + "\"?>\n");
437                 }
438                 //print(((Document)node).getDocumentElement());
439

440                 NodeList children = node.getChildNodes();
441                 for ( int iChild = 0; iChild < children.getLength(); iChild++ ) {
442                     print(children.item(iChild));
443                 }
444                 oPrtWritter.flush();
445                 break;
446             }
447
448             // print element with attributes
449
case Node.ELEMENT_NODE: {
450                 oPrtWritter.write('<');
451                 oPrtWritter.write(node.getNodeName());
452                 Attr attrs[] = sortAttributes(node.getAttributes());
453                 for ( int i = 0; i < attrs.length; i++ ) {
454                     Attr attr = attrs[i];
455                     oPrtWritter.write(' ');
456                     oPrtWritter.write(attr.getNodeName());
457                     oPrtWritter.write("=\"");
458                     oPrtWritter.write(normalize(attr.getNodeValue()));
459                     oPrtWritter.write('"');
460                 }
461                 oPrtWritter.write('>');
462                 NodeList children = node.getChildNodes();
463                 if ( children != null ) {
464                     int len = children.getLength();
465                     for ( int i = 0; i < len; i++ ) {
466                         print(children.item(i));
467                     }
468                 }
469                 break;
470             }
471
472             // handle entity reference nodes
473
case Node.ENTITY_REFERENCE_NODE: {
474                 if ( bCanonical ) {
475                     NodeList children = node.getChildNodes();
476                     if ( children != null ) {
477                         int len = children.getLength();
478                         for ( int i = 0; i < len; i++ ) {
479                             print(children.item(i));
480                         }
481                     }
482                 } else {
483                     oPrtWritter.write('&');
484                     oPrtWritter.write(node.getNodeName());
485                     oPrtWritter.write(';');
486                 }
487                 break;
488             }
489
490             // print cdata sections
491
case Node.CDATA_SECTION_NODE: {
492                 if ( bCanonical ) {
493                     oPrtWritter.write(normalize(node.getNodeValue()));
494                 } else {
495                     oPrtWritter.write("<![CDATA[");
496                     oPrtWritter.write(node.getNodeValue());
497                     oPrtWritter.write("]]>");
498                 }
499                 break;
500             }
501
502             // print text
503
case Node.TEXT_NODE: {
504                 oPrtWritter.write(normalize(node.getNodeValue()));
505                 break;
506             }
507
508             // print processing instruction
509
case Node.PROCESSING_INSTRUCTION_NODE: {
510                 oPrtWritter.write("<?");
511                 oPrtWritter.write(node.getNodeName());
512                 String JavaDoc data = node.getNodeValue();
513                 if ( data != null && data.length() > 0 ) {
514                     oPrtWritter.write(' ');
515                     oPrtWritter.write(data);
516                 }
517                 oPrtWritter.write("?>\n");
518                 break;
519             }
520         }
521
522         if ( type == Node.ELEMENT_NODE ) {
523             oPrtWritter.write("</");
524             oPrtWritter.write(node.getNodeName());
525             oPrtWritter.write('>');
526         }
527
528         oPrtWritter.flush();
529     } // print(Node)
530

531     //---------------------------------------------------------
532

533     private String JavaDoc normalize(String JavaDoc s) {
534         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
535
536         int len = (s != null) ? s.length() : 0;
537         for ( int i = 0; i < len; i++ ) {
538             char ch = s.charAt(i);
539             switch ( ch ) {
540             case '<': {
541                     str.append("&lt;");
542                     break;
543                 }
544             case '>': {
545                     str.append("&gt;");
546                     break;
547                 }
548             case '&': {
549                     str.append("&amp;");
550                     break;
551                 }
552             case '"': {
553                     str.append("&quot;");
554                     break;
555                 }
556             case '\'': {
557                     str.append("&apos;");
558                     break;
559                 }
560             case '\r':
561             case '\n': {
562                     if ( bCanonical ) {
563                         str.append("&#");
564                         str.append(Integer.toString(ch));
565                         str.append(';');
566                         break;
567                     }
568                     // else, default append char
569
}
570             default: {
571                     str.append(ch);
572                 }
573             }
574         }
575         return(str.toString());
576     } // normalize(String):String
577

578     //---------------------------------------------------------
579

580    protected Attr[] sortAttributes(NamedNodeMap attrs) {
581
582         int len = (attrs != null) ? attrs.getLength() : 0;
583         Attr array[] = new Attr[len];
584         for ( int i = 0; i < len; i++ ) {
585             array[i] = (Attr)attrs.item(i);
586         }
587         for ( int i = 0; i < len - 1; i++ ) {
588             String JavaDoc name = array[i].getNodeName();
589             int index = i;
590             for ( int j = i + 1; j < len; j++ ) {
591                 String JavaDoc curName = array[j].getNodeName();
592                 if ( curName.compareTo(name) < 0 ) {
593                     name = curName;
594                     index = j;
595                 }
596             }
597             if ( index != i ) {
598                 Attr temp = array[i];
599                 array[i] = array[index];
600                 array[index] = temp;
601             }
602         }
603         return(array);
604     } // sortAttributes(NamedNodeMap):Attr[]
605

606     //---------------------------------------------------------
607

608   public Vector JavaDoc filterChildsByName(Element oParent, String JavaDoc sChildsName) {
609     Element oContainers;
610     NodeList oNodeList;
611     Vector JavaDoc oLinkVctr;
612
613     // Obtener una referencia al nodo de nivel superior en el documento
614
Node oPageSetNode = getRootNode().getFirstChild();
615     if (oPageSetNode.getNodeName().equals("xml-stylesheet")) oPageSetNode = oPageSetNode.getNextSibling();
616
617     // Obtener una lista de nodos cuyo nombre sea <container>
618
oNodeList = oParent.getElementsByTagName(sChildsName);
619
620     // Crear el vector
621
oLinkVctr = new Vector JavaDoc(oNodeList.getLength());
622
623     // Convertir los nodos DOM en objetos de tipo Page
624
for (int i=0; i<oNodeList.getLength(); i++)
625       oLinkVctr.add(new DOMSubDocument (oNodeList.item(i)));
626
627     return oLinkVctr;
628   } // filterChildsByName()
629

630 } // DOMDocument
631
Popular Tags