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.
16 package org.wamblee.xml;
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
21 import org.apache.xml.serialize.OutputFormat;
22 import org.apache.xml.serialize.XMLSerializer;
24 import org.dom4j.DocumentException;
26 import org.dom4j.io.DOMReader;
27 import org.dom4j.io.DOMWriter;
29 import org.w3c.dom.Attr;
30 import org.w3c.dom.Document;
31 import org.w3c.dom.Element;
32 import org.w3c.dom.NamedNodeMap;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
36 import org.xml.sax.SAXException;
38 import java.io.ByteArrayInputStream;
39 import java.io.ByteArrayOutputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.OutputStream;
44 import java.util.ArrayList;
45 import java.util.List;
47 import java.util.TreeMap;
49 import javax.xml.XMLConstants;
50 import javax.xml.parsers.DocumentBuilder;
51 import javax.xml.parsers.DocumentBuilderFactory;
52 import javax.xml.parsers.ParserConfigurationException;
53 import javax.xml.transform.stream.StreamSource;
54 import javax.xml.validation.Schema;
55 import javax.xml.validation.SchemaFactory;
58 * Some basic XML utilities for common reoccuring tasks for DOM documents.
60 * @author Erik Brakkee
62 public final class DomUtils {
63 private static final Log LOG = LogFactory.getLog(DomUtils.class);
66 * Disabled default constructor.
74 * Parses an XML document from a string.
82 public static Document read(String aDocument) throws XMLException {
83 ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
89 * Parses an XML document from a stream.
97 public static Document read(InputStream aIs) throws XMLException {
99 DocumentBuilder builder = DocumentBuilderFactory.newInstance()
100 .newDocumentBuilder();
102 return builder.parse(aIs);
103 } catch (SAXException e) {
104 throw new XMLException(e.getMessage(), e);
105 } catch (IOException e) {
106 throw new XMLException(e.getMessage(), e);
107 } catch (ParserConfigurationException e) {
108 throw new XMLException(e.getMessage(), e);
112 } catch (Exception e) {
113 LOG.warn("Error closing XML file", e);
119 * Reads and validates a document against a schema.
126 * @return Parsed and validated document.
129 public static Document readAndValidate(InputStream aIs, InputStream aSchema)
130 throws XMLException {
132 final Schema schema = SchemaFactory.newInstance(
133 XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
134 new StreamSource(aSchema));
136 final DocumentBuilderFactory factory = DocumentBuilderFactory
138 factory.setValidating(true);
139 factory.setNamespaceAware(true);
140 factory.setSchema(schema);
142 return factory.newDocumentBuilder().parse(aIs);
143 } catch (SAXException e) {
144 throw new XMLException(e.getMessage(), e);
145 } catch (IOException e) {
146 throw new XMLException(e.getMessage(), e);
147 } catch (ParserConfigurationException e) {
148 throw new XMLException(e.getMessage(), e);
152 } catch (Exception e) {
153 LOG.warn("Error closing schema", e);
158 } catch (Exception e) {
159 LOG.warn("Error closing XML file", e);
165 * Serializes an XML document to a stream.
168 * Document to serialize.
173 public static void serialize(Document aDocument, OutputStream aOs)
175 XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
176 serializer.serialize(aDocument);
180 * Serializes an XML document.
183 * Document to serialize.
185 * @return Serialized document.
188 public static String serialize(Document aDocument) throws IOException {
189 ByteArrayOutputStream os = new ByteArrayOutputStream();
190 serialize(aDocument, os);
192 return os.toString();
196 * Converts a dom4j document into a w3c DOM document.
199 * Document to convert.
201 * @return W3C DOM document.
204 public static Document convert(org.dom4j.Document aDocument)
205 throws DocumentException {
206 return new DOMWriter().write(aDocument);
210 * Converts a W3C DOM document into a dom4j document.
213 * Document to convert.
215 * @return Dom4j document.
217 public static org.dom4j.Document convert(Document aDocument) {
218 return new DOMReader().read(aDocument);
222 * Removes duplicate attributes from a DOM tree.This is useful for
223 * postprocessing the output of JTidy as a workaround for a bug in JTidy.
226 * Node to remove duplicate attributes from (recursively).
227 * Attributes of the node itself are not dealt with. Only the
228 * child nodes are dealt with.
230 public static void removeDuplicateAttributes(Node aNode) {
231 NodeList list = aNode.getChildNodes();
233 for (int i = 0; i < list.getLength(); i++) {
234 Node node = list.item(i);
236 if (node instanceof Element) {
237 removeDuplicateAttributes((Element) node);
238 removeDuplicateAttributes(node);
244 * Removes duplicate attributes from an element.
249 private static void removeDuplicateAttributes(Element aElement) {
250 NamedNodeMap attributes = aElement.getAttributes();
251 Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
252 List<Attr> attlist = new ArrayList<Attr>();
254 for (int i = 0; i < attributes.getLength(); i++) {
255 Attr attribute = (Attr) attributes.item(i);
257 if (uniqueAttributes.containsKey(attribute.getNodeName())) {
258 LOG.info("Detected duplicate attribute (will be removed)'" +
259 attribute.getNodeName() + "'");
262 uniqueAttributes.put(attribute.getNodeName(), attribute);
263 attlist.add(attribute);
266 // Remove all attributes from the element.
267 for (Attr att : attlist) {
268 aElement.removeAttributeNode(att);
271 // Add the unique attributes back to the element.
272 for (Attr att : uniqueAttributes.values()) {
273 aElement.setAttributeNode(att);