2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.netconf.util.xml;
11 import com.google.common.base.Charsets;
12 import com.google.common.base.Optional;
13 import org.w3c.dom.Document;
14 import org.w3c.dom.Element;
15 import org.w3c.dom.Node;
16 import org.xml.sax.SAXException;
18 import javax.xml.XMLConstants;
19 import javax.xml.namespace.QName;
20 import javax.xml.parsers.DocumentBuilder;
21 import javax.xml.parsers.DocumentBuilderFactory;
22 import javax.xml.parsers.ParserConfigurationException;
23 import javax.xml.transform.OutputKeys;
24 import javax.xml.transform.Source;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.TransformerFactoryConfigurationError;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import javax.xml.transform.stream.StreamSource;
31 import javax.xml.validation.Schema;
32 import javax.xml.validation.SchemaFactory;
33 import javax.xml.xpath.XPathExpression;
34 import javax.xml.xpath.XPathExpressionException;
35 import java.io.ByteArrayInputStream;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.StringWriter;
42 public final class XmlUtil {
44 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
45 private static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
46 private static final DocumentBuilderFactory BUILDERFACTORY;
49 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
50 factory.setNamespaceAware(true);
51 factory.setCoalescing(true);
52 factory.setIgnoringElementContentWhitespace(true);
53 factory.setIgnoringComments(true);
54 BUILDERFACTORY = factory;
59 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
60 Document doc = readXmlToDocument(xmlContent);
61 return doc.getDocumentElement();
64 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
65 Document doc = readXmlToDocument(xmlContent);
66 return doc.getDocumentElement();
69 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
70 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
73 // TODO improve exceptions throwing
74 // along with XmlElement
76 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
77 DocumentBuilder dBuilder;
79 dBuilder = BUILDERFACTORY.newDocumentBuilder();
80 } catch (ParserConfigurationException e) {
81 throw new IllegalStateException("Failed to parse XML document", e);
83 Document doc = dBuilder.parse(xmlContent);
85 doc.getDocumentElement().normalize();
89 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
90 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
93 public static Document newDocument() {
95 DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
96 return builder.newDocument();
97 } catch (ParserConfigurationException e) {
98 throw new IllegalStateException("Failed to create document", e);
102 public static Element createElement(final Document document, String qName, Optional<String> namespaceURI) {
103 if(namespaceURI.isPresent()) {
104 final Element element = document.createElementNS(namespaceURI.get(), qName);
105 String name = XMLNS_ATTRIBUTE_KEY;
106 if(element.getPrefix() != null) {
107 name += ":" + element.getPrefix();
109 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
112 return document.createElement(qName);
115 public static Element createTextElement(Document document, String qName, String content, Optional<String> namespaceURI) {
116 Element typeElement = createElement(document, qName, namespaceURI);
117 typeElement.appendChild(document.createTextNode(content));
121 public static Element createPrefixedTextElement(Document document, String qName, String prefix, String content, Optional<String> namespace) {
122 return createTextElement(document, qName, createPrefixedValue(prefix, content), namespace);
125 public static String createPrefixedValue(String prefix, String value) {
126 return prefix + ":" + value;
129 public static String toString(Document document) {
130 return toString(document.getDocumentElement());
133 public static String toString(Element xml) {
134 return toString(xml, false);
137 public static String toString(XmlElement xmlElement) {
138 return toString(xmlElement.getDomElement(), false);
141 public static String toString(Element xml, boolean addXmlDeclaration) {
143 Transformer transformer = TransformerFactory.newInstance().newTransformer();
144 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
145 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
147 StreamResult result = new StreamResult(new StringWriter());
148 DOMSource source = new DOMSource(xml);
149 transformer.transform(source, result);
151 return result.getWriter().toString();
152 } catch (Exception | TransformerFactoryConfigurationError e) {
153 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
157 public static String toString(Document doc, boolean addXmlDeclaration) {
158 return toString(doc.getDocumentElement(), addXmlDeclaration);
161 public static Schema loadSchema(InputStream... fromStreams) {
162 Source[] sources = new Source[fromStreams.length];
164 for (InputStream stream : fromStreams) {
165 sources[i++] = new StreamSource(stream);
168 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
170 return schemaFactory.newSchema(sources);
171 } catch (SAXException e) {
172 throw new IllegalStateException("Failed to instantiate XML schema", e);
176 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
178 return expr.evaluate(rootNode, returnType);
179 } catch (XPathExpressionException e) {
180 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
184 public static Document createDocumentCopy(Document original) {
185 final Document copiedDocument = newDocument();
186 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
187 copiedDocument.appendChild(copiedRoot);
188 return copiedDocument;