001: /*
002: * Copyright 2001 Sun Microsystems, Inc. All rights reserved.
003: * PROPRIETARY/CONFIDENTIAL. Use of this product is subject to license terms.
004: */
005: package com.sun.portal.rewriter.util.xml;
006:
007: import org.w3c.dom.Document;
008: import org.w3c.dom.NamedNodeMap;
009: import org.w3c.dom.Node;
010: import org.w3c.dom.NodeList;
011: import org.xml.sax.SAXException;
012: import org.xml.sax.SAXParseException;
013:
014: import javax.xml.parsers.DocumentBuilder;
015: import javax.xml.parsers.DocumentBuilderFactory;
016: import javax.xml.parsers.ParserConfigurationException;
017: import javax.xml.transform.Result;
018: import javax.xml.transform.Source;
019: import javax.xml.transform.Transformer;
020: import javax.xml.transform.TransformerConfigurationException;
021: import javax.xml.transform.TransformerException;
022: import javax.xml.transform.TransformerFactory;
023: import javax.xml.transform.dom.DOMSource;
024: import javax.xml.transform.stream.StreamResult;
025: import java.io.File;
026: import java.io.IOException;
027:
028: public class DOMUtil {
029: /** Prints the specified node, then prints all of its children. */
030: public static void printDOM(Node node) {
031: int type = node.getNodeType();
032: switch (type) {
033: // print the document element
034: case Node.DOCUMENT_NODE: {
035: System.out.println("<?xml version=\"1.0\" ?>");
036: printDOM(((Document) node).getDocumentElement());
037: break;
038: }
039:
040: // print element with attributes
041: case Node.ELEMENT_NODE: {
042: System.out.print("<");
043: System.out.print(node.getNodeName());
044: NamedNodeMap attrs = node.getAttributes();
045: for (int i = 0; i < attrs.getLength(); i++) {
046: Node attr = attrs.item(i);
047: System.out.print(" " + attr.getNodeName().trim()
048: + "=\"" + attr.getNodeValue().trim() + "\"");
049: }
050: System.out.println(">");
051:
052: NodeList children = node.getChildNodes();
053: if (children != null) {
054: int len = children.getLength();
055: for (int i = 0; i < len; i++) {
056: printDOM(children.item(i));
057: }
058: }
059:
060: break;
061: }
062:
063: // handle entity reference nodes
064: case Node.ENTITY_REFERENCE_NODE: {
065: System.out.print("&");
066: System.out.print(node.getNodeName().trim());
067: System.out.print(";");
068: break;
069: }
070:
071: // print cdata sections
072: case Node.CDATA_SECTION_NODE: {
073: System.out.print("");
074: break;
075: }
076:
077: // print text
078: case Node.TEXT_NODE: {
079: System.out.print(node.getNodeValue().trim());
080: break;
081: }
082:
083: // print processing instruction
084: case Node.PROCESSING_INSTRUCTION_NODE: {
085: System.out.print("");
086: break;
087: }
088: }
089:
090: if (type == Node.ELEMENT_NODE) {
091: System.out.println();
092: System.out.print("'");
093: }
094: }//printDOM()
095:
096: /**
097: * Parse the XML file and create Document
098: * @param fileName
099: * @return Document
100: */
101: public static Document parse(String fileName) {
102: Document document = null;
103: // Initiate DocumentBuilderFactory
104: DocumentBuilderFactory factory = DocumentBuilderFactory
105: .newInstance();
106:
107: // To get a validating parser
108: factory.setValidating(false);
109: // To get one that understands namespaces
110: factory.setNamespaceAware(true);
111:
112: try {
113: // Get DocumentBuilder
114: DocumentBuilder builder = factory.newDocumentBuilder();
115: // Parse and load into memory the Document
116: document = builder.parse(new File(fileName));
117: return document;
118:
119: } catch (SAXParseException spe) {
120: // Error generated by the parser
121: System.out.println("\n** Parsing error , line "
122: + spe.getLineNumber() + ", uri "
123: + spe.getSystemId());
124: System.out.println(" " + spe.getMessage());
125: // Use the contained exception, if any
126: Exception x = spe;
127: if (spe.getException() != null)
128: x = spe.getException();
129: x.printStackTrace();
130: } catch (SAXException sxe) {
131: // Error generated during parsing
132: Exception x = sxe;
133: if (sxe.getException() != null)
134: x = sxe.getException();
135: x.printStackTrace();
136: } catch (ParserConfigurationException pce) {
137: // Parser with specified options can't be built
138: pce.printStackTrace();
139: } catch (IOException ioe) {
140: // I/O error
141: ioe.printStackTrace();
142: }
143:
144: return null;
145: }//parse()
146:
147: /**
148: * This method writes a DOM document to a file
149: * @param filename
150: * @param document
151: */
152: public static void writeXmlToFile(String filename, Document document) {
153: try {
154: // Prepare the DOM document for writing
155: Source source = new DOMSource(document);
156:
157: // Prepare the output file
158: File file = new File(filename);
159: Result result = new StreamResult(file);
160:
161: // Write the DOM document to the file
162: // Get Transformer
163: Transformer xformer = TransformerFactory.newInstance()
164: .newTransformer();
165: // Write to a file
166: xformer.transform(source, result);
167: } catch (TransformerConfigurationException e) {
168: System.out.println("TransformerConfigurationException: "
169: + e);
170: } catch (TransformerException e) {
171: System.out.println("TransformerException: " + e);
172: }
173: }//writeXmlToFile()
174:
175: /**
176: * Count Elements in Document by Tag Name
177: * @param tag
178: * @param document
179: * @return number elements by Tag Name
180: */
181: public static int countByTagName(String tag, Document document) {
182: NodeList list = document.getElementsByTagName(tag);
183: return list.getLength();
184: }//countByTagName()
185: }//class DOMUtil
|