2 * Copyright 2005 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.wamblee.xml;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
28 import org.apache.xml.serialize.OutputFormat;
29 import org.apache.xml.serialize.XMLSerializer;
30 import org.dom4j.DocumentException;
31 import org.dom4j.io.DOMReader;
32 import org.dom4j.io.DOMWriter;
33 import org.w3c.dom.Document;
34 import org.xml.sax.SAXException;
37 * Some basic XML utilities for common reoccuring tasks for
40 public final class DomUtils {
43 * Disabled default constructor.
52 * Parses an XML document from a stream.
53 * @param aIs Input stream.
56 public static Document read(InputStream aIs) throws SAXException, ParserConfigurationException, IOException {
57 DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
58 return builder.parse(aIs);
62 * Serializes an XML document to a stream.
63 * @param aDocument Document to serialize.
64 * @param aOs Output stream.
66 public static void serialize(Document aDocument, OutputStream aOs) throws IOException {
67 XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
68 serializer.serialize(aDocument);
72 * Serializes an XML document.
73 * @param aDocument Document to serialize.
74 * @return Serialized document.
76 public static String serialize(Document aDocument) throws IOException {
77 ByteArrayOutputStream os = new ByteArrayOutputStream();
78 serialize(aDocument, os);
83 * Converts a dom4j document into a w3c DOM document.
84 * @param aDocument Document to convert.
85 * @return W3C DOM document.
87 public static Document convert(org.dom4j.Document aDocument) throws DocumentException {
88 return new DOMWriter().write(aDocument);
92 * Converts a W3C DOM document into a dom4j document.
93 * @param aDocument Document to convert.
94 * @return Dom4j document.
96 public static org.dom4j.Document convert(Document aDocument) {
97 return new DOMReader().read(aDocument);