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 public final class DomUtils {
57 private static final Log LOG = LogFactory.getLog(DomUtils.class);
60 * Disabled default constructor.
68 * Parses an XML document from a string.
74 public static Document read(String aDocument) throws XMLException {
75 ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
80 * Parses an XML document from a stream.
86 public static Document read(InputStream aIs) throws XMLException {
88 DocumentBuilder builder = DocumentBuilderFactory.newInstance()
89 .newDocumentBuilder();
90 return builder.parse(aIs);
91 } catch (SAXException e) {
92 throw new XMLException(e.getMessage(), e);
93 } catch (IOException e) {
94 throw new XMLException(e.getMessage(), e);
95 } catch (ParserConfigurationException e) {
96 throw new XMLException(e.getMessage(), e);
100 } catch (Exception e) {
101 LOG.warn("Error closing XML file", e);
107 * Reads and validates a document against a schema.
113 * @return Parsed and validated document.
115 public static Document readAndValidate(InputStream aIs, InputStream aSchema)
116 throws XMLException {
119 final Schema schema = SchemaFactory.newInstance(
120 XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
121 new StreamSource(aSchema));
123 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
124 factory.setValidating(true);
125 factory.setNamespaceAware(true);
126 factory.setSchema(schema);
128 return factory.newDocumentBuilder().parse(aIs);
129 } catch (SAXException e) {
130 throw new XMLException(e.getMessage(), e);
131 } catch (IOException e) {
132 throw new XMLException(e.getMessage(), e);
133 } catch (ParserConfigurationException e) {
134 throw new XMLException(e.getMessage(), e);
138 } catch (Exception e) {
139 LOG.warn("Error closing schema", e);
143 } catch (Exception e) {
144 LOG.warn("Error closing XML file", e);
151 * Serializes an XML document to a stream.
154 * Document to serialize.
158 public static void serialize(Document aDocument, OutputStream aOs)
160 XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
161 serializer.serialize(aDocument);
165 * Serializes an XML document.
168 * Document to serialize.
169 * @return Serialized document.
171 public static String serialize(Document aDocument) throws IOException {
172 ByteArrayOutputStream os = new ByteArrayOutputStream();
173 serialize(aDocument, os);
174 return os.toString();
178 * Converts a dom4j document into a w3c DOM document.
181 * Document to convert.
182 * @return W3C DOM document.
184 public static Document convert(org.dom4j.Document aDocument)
185 throws DocumentException {
186 return new DOMWriter().write(aDocument);
190 * Converts a W3C DOM document into a dom4j document.
193 * Document to convert.
194 * @return Dom4j document.
196 public static org.dom4j.Document convert(Document aDocument) {
197 return new DOMReader().read(aDocument);
201 * Removes duplicate attributes from a DOM tree.This is useful for
202 * postprocessing the output of JTidy as a workaround for a bug in JTidy.
205 * Node to remove duplicate attributes from (recursively).
206 * Attributes of the node itself are not dealt with. Only the
207 * child nodes are dealt with.
209 public static void removeDuplicateAttributes(Node aNode) {
210 NodeList list = aNode.getChildNodes();
211 for (int i = 0; i < list.getLength(); i++) {
212 Node node = list.item(i);
213 if (node instanceof Element) {
214 removeDuplicateAttributes((Element) node);
215 removeDuplicateAttributes(node);
221 * Removes duplicate attributes from an element.
226 private static void removeDuplicateAttributes(Element aElement) {
227 NamedNodeMap attributes = aElement.getAttributes();
228 Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
229 List<Attr> attlist = new ArrayList<Attr>();
230 for (int i = 0; i < attributes.getLength(); i++) {
231 Attr attribute = (Attr) attributes.item(i);
232 if (uniqueAttributes.containsKey(attribute.getNodeName())) {
233 LOG.info("Detected duplicate attribute (will be removed)'"
234 + attribute.getNodeName() + "'");
236 uniqueAttributes.put(attribute.getNodeName(), attribute);
237 attlist.add(attribute);
239 // Remove all attributes from the element.
240 for (Attr att : attlist) {
241 aElement.removeAttributeNode(att);
243 // Add the unique attributes back to the element.
244 for (Attr att : uniqueAttributes.values()) {
245 aElement.setAttributeNode(att);