KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > xml > DocumentHelper


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17
18 /* $Id: DocumentHelper.java 43153 2004-07-29 16:09:29Z andreas $ */
19
20 package org.apache.lenya.xml;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.Writer JavaDoc;
26 import java.net.URI JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.List JavaDoc;
30
31 import javax.xml.parsers.DocumentBuilder JavaDoc;
32 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
33 import javax.xml.parsers.ParserConfigurationException JavaDoc;
34 import javax.xml.transform.OutputKeys JavaDoc;
35 import javax.xml.transform.Transformer JavaDoc;
36 import javax.xml.transform.TransformerConfigurationException JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.TransformerFactory JavaDoc;
39 import javax.xml.transform.dom.DOMSource JavaDoc;
40 import javax.xml.transform.stream.StreamResult JavaDoc;
41
42 import org.apache.xml.resolver.tools.CatalogResolver;
43 import org.w3c.dom.DOMException JavaDoc;
44 import org.w3c.dom.Document JavaDoc;
45 import org.w3c.dom.DocumentType JavaDoc;
46 import org.w3c.dom.Element JavaDoc;
47 import org.w3c.dom.Node JavaDoc;
48 import org.w3c.dom.NodeList JavaDoc;
49 import org.w3c.dom.Text JavaDoc;
50 import org.xml.sax.SAXException JavaDoc;
51
52
53 /**
54  * Various utility methods to work with JAXP.
55  */

56 public class DocumentHelper {
57     /**
58      * Creates a non-validating and namespace-aware DocumentBuilder.
59      *
60      * @return A new DocumentBuilder object.
61      * @throws ParserConfigurationException if an error occurs
62      */

63     public static DocumentBuilder JavaDoc createBuilder() throws ParserConfigurationException JavaDoc {
64         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
65         factory.setNamespaceAware(true);
66         DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
67
68         CatalogResolver cr = new CatalogResolver();
69         builder.setEntityResolver(cr);
70         return builder;
71     }
72
73     /**
74      * Creates a document. A xmlns:prefix="namespaceUri" attribute is added to
75      * the document element.
76      *
77      * @param namespaceUri The namespace URL of the root element.
78      * @param qualifiedName The qualified name of the root element.
79      * @param documentType The type of document to be created or null. When doctype is not null,
80      * its Node.ownerDocument attribute is set to the document being created.
81      * @return A new Document object.
82      *
83      * @throws DOMException if an error occurs
84      * @throws ParserConfigurationException if an error occurs
85      *
86      * @see org.w3c.dom.DOMImplementation#createDocument(String, String, DocumentType)
87      */

88     public static Document JavaDoc createDocument(String JavaDoc namespaceUri, String JavaDoc qualifiedName,
89         DocumentType JavaDoc documentType) throws DOMException JavaDoc, ParserConfigurationException JavaDoc {
90         DocumentBuilder JavaDoc builder = createBuilder();
91         Document JavaDoc document = builder.getDOMImplementation().createDocument(namespaceUri,
92                 qualifiedName, documentType);
93
94         // add xmlns:prefix attribute
95
String JavaDoc name = "xmlns";
96         int index = qualifiedName.indexOf(":");
97
98         if (index > -1) {
99             name += (":" + qualifiedName.substring(0, index));
100         }
101
102         document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", name, namespaceUri);
103
104         return document;
105     }
106
107     /**
108      * Reads a document from a file.
109      * @return A document.
110      * @param file The file to load the document from.
111      *
112      * @throws ParserConfigurationException if an error occurs
113      * @throws SAXException if an error occurs
114      * @throws IOException if an error occurs
115      */

116     public static Document JavaDoc readDocument(File JavaDoc file)
117         throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
118         DocumentBuilder JavaDoc builder = createBuilder();
119         return builder.parse(file);
120     }
121
122     /**
123      * Reads a document from a URL.
124      * @return A document.
125      * @param url The URL to load the document from.
126      *
127      * @throws ParserConfigurationException if an error occurs
128      * @throws SAXException if an error occurs
129      * @throws IOException if an error occurs
130      */

131     public static Document JavaDoc readDocument(URL JavaDoc url)
132         throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
133         DocumentBuilder JavaDoc builder = createBuilder();
134         return builder.parse(url.toString());
135     }
136
137     /**
138      * Reads a document from a URI.
139      * @return A document.
140      * @param uri The URI to load the document from.
141      *
142      * @throws ParserConfigurationException if an error occurs
143      * @throws SAXException if an error occurs
144      * @throws IOException if an error occurs
145      */

146     public static Document JavaDoc readDocument(URI JavaDoc uri)
147         throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
148         DocumentBuilder JavaDoc builder = createBuilder();
149         return builder.parse(uri.toString());
150     }
151
152     /**
153      * Reads a document from a string.
154      * @return A document.
155      * @param string The string to load the document from.
156      *
157      * @throws ParserConfigurationException if an error occurs
158      * @throws SAXException if an error occurs
159      * @throws IOException if an error occurs
160      */

161     public static Document JavaDoc readDocument(String JavaDoc string)
162         throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
163         DocumentBuilder JavaDoc builder = createBuilder();
164         return builder.parse(string);
165     }
166
167     /**
168      * Reads a document from an input stream.
169      * @return A document.
170      * @param stream The input stream to load the document from.
171      *
172      * @throws ParserConfigurationException if an error occurs
173      * @throws SAXException if an error occurs
174      * @throws IOException if an error occurs
175      */

176     public static Document JavaDoc readDocument(InputStream JavaDoc stream)
177         throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc {
178         DocumentBuilder JavaDoc builder = createBuilder();
179         return builder.parse(stream);
180     }
181
182     /**
183      * Writes a document to a file. A new file is created if it does not exist.
184      *
185      * @param document The document to save.
186      * @param file The file to save the document to.
187      *
188      * @throws IOException if an error occurs
189      * @throws TransformerConfigurationException if an error occurs
190      * @throws TransformerException if an error occurs
191      */

192     public static void writeDocument(Document JavaDoc document, File JavaDoc file)
193         throws TransformerConfigurationException JavaDoc, TransformerException JavaDoc, IOException JavaDoc {
194         file.getParentFile().mkdirs();
195         file.createNewFile();
196
197         DOMSource JavaDoc source = new DOMSource JavaDoc(document);
198         StreamResult JavaDoc result = new StreamResult JavaDoc(file);
199         getTransformer(document.getDoctype()).transform(source, result);
200     }
201
202     /**
203      * Writes a document to a writer.
204      *
205      * @param document The document to write.
206      * @param writer The writer to write the document to.
207      *
208      * @throws IOException if an error occurs
209      * @throws TransformerConfigurationException if an error occurs
210      * @throws TransformerException if an error occurs
211      */

212     public static void writeDocument(Document JavaDoc document, Writer JavaDoc writer)
213         throws TransformerConfigurationException JavaDoc, TransformerException JavaDoc, IOException JavaDoc {
214         DOMSource JavaDoc source = new DOMSource JavaDoc(document);
215         StreamResult JavaDoc result = new StreamResult JavaDoc(writer);
216         getTransformer(document.getDoctype()).transform(source, result);
217     }
218
219     /**
220      * Get the tranformer.
221      *
222      * @param documentType the document type
223      * @return a transformer
224      *
225      * @throws TransformerConfigurationException if an error occurs
226      */

227     protected static Transformer JavaDoc getTransformer(DocumentType JavaDoc documentType)
228         throws TransformerConfigurationException JavaDoc {
229         TransformerFactory JavaDoc factory = TransformerFactory.newInstance();
230         Transformer JavaDoc transformer = factory.newTransformer();
231         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
232         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
233
234         if (documentType != null) {
235             transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, documentType.getPublicId());
236             transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, documentType.getSystemId());
237         }
238
239         return transformer;
240     }
241
242     /**
243      * Creates a document type.
244      *
245      * @param qualifiedName The qualified name of the document type.
246      * @param publicId The public identifier.
247      * @param systemId The system identifier.
248      *
249      * @return the document type
250      *
251      * @throws ParserConfigurationException if an error occurs
252      *
253      * @see org.w3c.dom.DOMImplementation#createDocumentType(java.lang.String, java.lang.String, java.lang.String)
254      */

255     public DocumentType JavaDoc createDocumentType(String JavaDoc qualifiedName, String JavaDoc publicId, String JavaDoc systemId)
256         throws ParserConfigurationException JavaDoc {
257         DocumentBuilder JavaDoc builder = createBuilder();
258
259         return builder.getDOMImplementation().createDocumentType(qualifiedName, publicId, systemId);
260     }
261
262     /**
263      * Returns the first child element of an element that belong to a certain namespace
264      * or <code>null</code> if none exists.
265      * @param element The parent element.
266      * @param namespaceUri The namespace that the childen must belong to.
267      * @return The first child element or <code>null</code> if none exists.
268      */

269     public static Element JavaDoc getFirstChild(Element JavaDoc element, String JavaDoc namespaceUri) {
270         return getFirstChild(element, namespaceUri, "*");
271     }
272
273     /**
274      * Returns the first child element of an element that belongs to a certain namespace
275      * and has a certain local name or <code>null</code> if none exists.
276      *
277      * @param element The parent element.
278      * @param namespaceUri The namespace that the childen must belong to.
279      * @param localName The local name of the children.
280      *
281      * @return The child element or <code>null</code> if none exists.
282      */

283     public static Element JavaDoc getFirstChild(Element JavaDoc element, String JavaDoc namespaceUri, String JavaDoc localName) {
284         Element JavaDoc[] children = getChildren(element, namespaceUri, localName);
285
286         if (children.length > 0) {
287             return children[0];
288         } else {
289             return null;
290         }
291     }
292
293     /**
294      * Returns all child elements of an element, regardless of the namespace.
295      * @param element The parent element.
296      * @return The child elements.
297      */

298     public static Element JavaDoc[] getChildren(Element JavaDoc element) {
299         List JavaDoc childElements = new ArrayList JavaDoc();
300         NodeList JavaDoc children = element.getElementsByTagName("*");
301
302         for (int i = 0; i < children.getLength(); i++) {
303             if (children.item(i).getParentNode() == element) {
304                 childElements.add(children.item(i));
305             }
306         }
307
308         return (Element JavaDoc[]) childElements.toArray(new Element JavaDoc[childElements.size()]);
309     }
310
311     /**
312      * Returns all child elements of an element that belong to a certain namespace.
313      *
314      * @param element The parent element.
315      * @param namespaceUri The namespace that the childen must belong to.
316      *
317      * @return The child elements.
318      */

319     public static Element JavaDoc[] getChildren(Element JavaDoc element, String JavaDoc namespaceUri) {
320         return getChildren(element, namespaceUri, "*");
321     }
322
323     /**
324      * Returns all child elements of an element that belong to a certain namespace
325      * and have a certain local name.
326      *
327      * @param element The parent element.
328      * @param namespaceUri The namespace that the childen must belong to.
329      * @param localName The local name of the children.
330      *
331      * @return The child elements.
332      */

333     public static Element JavaDoc[] getChildren(Element JavaDoc element, String JavaDoc namespaceUri, String JavaDoc localName) {
334         List JavaDoc childElements = new ArrayList JavaDoc();
335         NodeList JavaDoc children = element.getElementsByTagNameNS(namespaceUri, localName);
336
337         for (int i = 0; i < children.getLength(); i++) {
338             if (children.item(i).getParentNode() == element) {
339                 childElements.add(children.item(i));
340             }
341         }
342
343         return (Element JavaDoc[]) childElements.toArray(new Element JavaDoc[childElements.size()]);
344     }
345
346     /**
347      * Returns the text inside an element. Only the child text nodes of this
348      * element are collected.
349      * @param element The element.
350      * @return The text inside the element.
351      */

352     public static String JavaDoc getSimpleElementText(Element JavaDoc element) {
353         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
354         NodeList JavaDoc children = element.getChildNodes();
355
356         for (int i = 0; i < children.getLength(); i++) {
357             Node JavaDoc child = children.item(i);
358
359             if (child instanceof Text JavaDoc) {
360                 buffer.append(child.getNodeValue());
361             }
362         }
363
364         return buffer.toString();
365     }
366
367     /**
368      * Replaces all child nodes of an element by a single text node.
369      *
370      * @param element The element.
371      * @param text The text to insert.
372      */

373     public static void setSimpleElementText(Element JavaDoc element, String JavaDoc text) {
374         NodeList JavaDoc children = element.getChildNodes();
375
376         for (int i = 0; i < children.getLength(); i++) {
377             Node JavaDoc child = children.item(i);
378             element.removeChild(child);
379         }
380         
381         Node JavaDoc textNode = element.getOwnerDocument().createTextNode(text);
382         element.appendChild(textNode);
383     }
384
385
386     /**
387      * Returns all following sibling elements of an element that belong to a certain namespace.
388      *
389      * @param element The parent element.
390      * @param namespaceUri The namespace that the childen must belong to.
391      *
392      * @return The following sibling elements.
393      */

394     public static Element JavaDoc[] getNextSiblings(Element JavaDoc element, String JavaDoc namespaceUri) {
395         return getNextSiblings(element, namespaceUri, "*");
396     }
397
398     /**
399      * Returns all following sibling elements of an element that belong to a certain namespace.
400      * and have a certain local name.
401      *
402      * @param element The parent element.
403      * @param namespaceUri The namespace that the childen must belong to.
404      * @param localName The local name of the children.
405      *
406      * @return The following sibling elements.
407      */

408     public static Element JavaDoc[] getNextSiblings(Element JavaDoc element, String JavaDoc namespaceUri, String JavaDoc localName) {
409         List JavaDoc childElements = new ArrayList JavaDoc();
410         Element JavaDoc parent = (Element JavaDoc) element.getParentNode();
411         Element JavaDoc[] children=getChildren(parent, namespaceUri, localName);
412          
413         int l = children.length;
414         for (int i = 0; i < children.length; i++) {
415             if (children[i] == element) {
416                 l = i;
417             }
418             if (i>l){
419                 childElements.add(children[i]);
420             }
421         }
422
423         return (Element JavaDoc[]) childElements.toArray(new Element JavaDoc[childElements.size()]);
424     }
425 }
426
Popular Tags