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 java.io.ByteArrayInputStream;
15 import java.io.FileInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.StringWriter;
19 import javax.xml.XMLConstants;
20 import javax.xml.namespace.QName;
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Source;
26 import javax.xml.transform.Transformer;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.TransformerFactoryConfigurationError;
29 import javax.xml.transform.dom.DOMSource;
30 import javax.xml.transform.stream.StreamResult;
31 import javax.xml.transform.stream.StreamSource;
32 import javax.xml.validation.Schema;
33 import javax.xml.validation.SchemaFactory;
34 import javax.xml.xpath.XPathExpression;
35 import javax.xml.xpath.XPathExpressionException;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38 import org.w3c.dom.Node;
39 import org.xml.sax.SAXException;
41 public final class XmlUtil {
43 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
44 public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
45 private static final DocumentBuilderFactory BUILDERFACTORY;
48 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
49 factory.setNamespaceAware(true);
50 factory.setCoalescing(true);
51 factory.setIgnoringElementContentWhitespace(true);
52 factory.setIgnoringComments(true);
53 BUILDERFACTORY = factory;
58 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
59 Document doc = readXmlToDocument(xmlContent);
60 return doc.getDocumentElement();
63 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
64 Document doc = readXmlToDocument(xmlContent);
65 return doc.getDocumentElement();
68 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
69 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
72 // TODO improve exceptions throwing
73 // along with XmlElement
75 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
76 DocumentBuilder dBuilder;
78 dBuilder = BUILDERFACTORY.newDocumentBuilder();
79 } catch (ParserConfigurationException e) {
80 throw new IllegalStateException("Failed to parse XML document", e);
82 Document doc = dBuilder.parse(xmlContent);
84 doc.getDocumentElement().normalize();
88 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
89 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
92 public static Document newDocument() {
94 DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
95 return builder.newDocument();
96 } catch (ParserConfigurationException e) {
97 throw new IllegalStateException("Failed to create document", e);
101 public static Element createElement(final Document document, String qName, Optional<String> namespaceURI) {
102 if(namespaceURI.isPresent()) {
103 final Element element = document.createElementNS(namespaceURI.get(), qName);
104 String name = XMLNS_ATTRIBUTE_KEY;
105 if(element.getPrefix() != null) {
106 name += ":" + element.getPrefix();
108 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
111 return document.createElement(qName);
114 public static Element createTextElement(Document document, String qName, String content, Optional<String> namespaceURI) {
115 Element typeElement = createElement(document, qName, namespaceURI);
116 typeElement.appendChild(document.createTextNode(content));
120 public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
121 String namespace, String contentWithoutPrefix) {
123 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
124 Element element = createTextElement(document, qName, content, Optional.<String>absent());
125 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
126 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
130 public static String createPrefixedValue(String prefix, String value) {
131 return prefix + ":" + value;
134 public static String toString(Document document) {
135 return toString(document.getDocumentElement());
138 public static String toString(Element xml) {
139 return toString(xml, false);
142 public static String toString(XmlElement xmlElement) {
143 return toString(xmlElement.getDomElement(), false);
146 public static String toString(Element xml, boolean addXmlDeclaration) {
148 Transformer transformer = TransformerFactory.newInstance().newTransformer();
149 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
150 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
152 StreamResult result = new StreamResult(new StringWriter());
153 DOMSource source = new DOMSource(xml);
154 transformer.transform(source, result);
156 return result.getWriter().toString();
157 } catch (Exception | TransformerFactoryConfigurationError e) {
158 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
162 public static String toString(Document doc, boolean addXmlDeclaration) {
163 return toString(doc.getDocumentElement(), addXmlDeclaration);
166 public static Schema loadSchema(InputStream... fromStreams) {
167 Source[] sources = new Source[fromStreams.length];
169 for (InputStream stream : fromStreams) {
170 sources[i++] = new StreamSource(stream);
173 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
175 return schemaFactory.newSchema(sources);
176 } catch (SAXException e) {
177 throw new IllegalStateException("Failed to instantiate XML schema", e);
181 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
183 return expr.evaluate(rootNode, returnType);
184 } catch (XPathExpressionException e) {
185 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
189 public static Document createDocumentCopy(Document original) {
190 final Document copiedDocument = newDocument();
191 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
192 copiedDocument.appendChild(copiedRoot);
193 return copiedDocument;