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.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.util.ArrayList;
25 import java.util.List;
27 import java.util.TreeMap;
29 import javax.xml.XMLConstants;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.transform.stream.StreamSource;
34 import javax.xml.validation.Schema;
35 import javax.xml.validation.SchemaFactory;
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.apache.xml.serialize.OutputFormat;
40 import org.apache.xml.serialize.XMLSerializer;
41 import org.dom4j.DocumentException;
42 import org.dom4j.io.DOMReader;
43 import org.dom4j.io.DOMWriter;
44 import org.w3c.dom.Attr;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47 import org.w3c.dom.NamedNodeMap;
48 import org.w3c.dom.Node;
49 import org.w3c.dom.NodeList;
50 import org.xml.sax.SAXException;
53 * Some basic XML utilities for common reoccuring tasks for DOM documents.
55 * @author Erik Brakkee
57 public final class DomUtils {
59 private static final Log LOG = LogFactory.getLog(DomUtils.class);
62 * Disabled default constructor.
70 * Parses an XML document from a string.
76 public static Document read(String aDocument) throws XMLException {
77 ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
82 * Parses an XML document from a stream.
88 public static Document read(InputStream aIs) throws XMLException {
90 DocumentBuilder builder = DocumentBuilderFactory.newInstance()
91 .newDocumentBuilder();
92 return builder.parse(aIs);
93 } catch (SAXException e) {
94 throw new XMLException(e.getMessage(), e);
95 } catch (IOException e) {
96 throw new XMLException(e.getMessage(), e);
97 } catch (ParserConfigurationException e) {
98 throw new XMLException(e.getMessage(), e);
102 } catch (Exception e) {
103 LOG.warn("Error closing XML file", e);
109 * Reads and validates a document against a schema.
115 * @return Parsed and validated document.
117 public static Document readAndValidate(InputStream aIs, InputStream aSchema)
118 throws XMLException {
121 final Schema schema = SchemaFactory.newInstance(
122 XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
123 new StreamSource(aSchema));
125 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
126 factory.setValidating(true);
127 factory.setNamespaceAware(true);
128 factory.setSchema(schema);
130 return factory.newDocumentBuilder().parse(aIs);
131 } catch (SAXException e) {
132 throw new XMLException(e.getMessage(), e);
133 } catch (IOException e) {
134 throw new XMLException(e.getMessage(), e);
135 } catch (ParserConfigurationException e) {
136 throw new XMLException(e.getMessage(), e);
140 } catch (Exception e) {
141 LOG.warn("Error closing schema", e);
145 } catch (Exception e) {
146 LOG.warn("Error closing XML file", e);
153 * Serializes an XML document to a stream.
156 * Document to serialize.
160 public static void serialize(Document aDocument, OutputStream aOs)
162 XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
163 serializer.serialize(aDocument);
167 * Serializes an XML document.
170 * Document to serialize.
171 * @return Serialized document.
173 public static String serialize(Document aDocument) throws IOException {
174 ByteArrayOutputStream os = new ByteArrayOutputStream();
175 serialize(aDocument, os);
176 return os.toString();
180 * Converts a dom4j document into a w3c DOM document.
183 * Document to convert.
184 * @return W3C DOM document.
186 public static Document convert(org.dom4j.Document aDocument)
187 throws DocumentException {
188 return new DOMWriter().write(aDocument);
192 * Converts a W3C DOM document into a dom4j document.
195 * Document to convert.
196 * @return Dom4j document.
198 public static org.dom4j.Document convert(Document aDocument) {
199 return new DOMReader().read(aDocument);
203 * Removes duplicate attributes from a DOM tree.This is useful for
204 * postprocessing the output of JTidy as a workaround for a bug in JTidy.
207 * Node to remove duplicate attributes from (recursively).
208 * Attributes of the node itself are not dealt with. Only the
209 * child nodes are dealt with.
211 public static void removeDuplicateAttributes(Node aNode) {
212 NodeList list = aNode.getChildNodes();
213 for (int i = 0; i < list.getLength(); i++) {
214 Node node = list.item(i);
215 if (node instanceof Element) {
216 removeDuplicateAttributes((Element) node);
217 removeDuplicateAttributes(node);
223 * Removes duplicate attributes from an element.
228 private static void removeDuplicateAttributes(Element aElement) {
229 NamedNodeMap attributes = aElement.getAttributes();
230 Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
231 List<Attr> attlist = new ArrayList<Attr>();
232 for (int i = 0; i < attributes.getLength(); i++) {
233 Attr attribute = (Attr) attributes.item(i);
234 if (uniqueAttributes.containsKey(attribute.getNodeName())) {
235 LOG.info("Detected duplicate attribute (will be removed)'"
236 + attribute.getNodeName() + "'");
238 uniqueAttributes.put(attribute.getNodeName(), attribute);
239 attlist.add(attribute);
241 // Remove all attributes from the element.
242 for (Attr att : attlist) {
243 aElement.removeAttributeNode(att);
245 // Add the unique attributes back to the element.
246 for (Attr att : uniqueAttributes.values()) {
247 aElement.setAttributeNode(att);