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.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.Element;
39 import org.w3c.dom.Node;
40 import org.xml.sax.SAXException;
42 public final class XmlUtil {
44 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
45 public 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 createTextElementWithNamespacedContent(Document document, String qName, String prefix,
122 String namespace, String contentWithoutPrefix) {
124 return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
127 public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
128 String namespace, String contentWithoutPrefix, Optional<String> namespaceURI) {
130 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
131 Element element = createTextElement(document, qName, content, namespaceURI);
132 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
133 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
137 public static String createPrefixedValue(String prefix, String value) {
138 return prefix + ":" + value;
141 public static String toString(Document document) {
142 return toString(document.getDocumentElement());
145 public static String toString(Element xml) {
146 return toString(xml, false);
149 public static String toString(XmlElement xmlElement) {
150 return toString(xmlElement.getDomElement(), false);
153 public static String toString(Element xml, boolean addXmlDeclaration) {
155 Transformer transformer = TransformerFactory.newInstance().newTransformer();
156 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
157 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
159 StreamResult result = new StreamResult(new StringWriter());
160 DOMSource source = new DOMSource(xml);
161 transformer.transform(source, result);
163 return result.getWriter().toString();
164 } catch (Exception | TransformerFactoryConfigurationError e) {
165 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
169 public static String toString(Document doc, boolean addXmlDeclaration) {
170 return toString(doc.getDocumentElement(), addXmlDeclaration);
173 public static Schema loadSchema(InputStream... fromStreams) {
174 Source[] sources = new Source[fromStreams.length];
176 for (InputStream stream : fromStreams) {
177 sources[i++] = new StreamSource(stream);
180 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
182 return schemaFactory.newSchema(sources);
183 } catch (SAXException e) {
184 throw new IllegalStateException("Failed to instantiate XML schema", e);
188 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
190 return expr.evaluate(rootNode, returnType);
191 } catch (XPathExpressionException e) {
192 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
196 public static Document createDocumentCopy(Document original) {
197 final Document copiedDocument = newDocument();
198 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
199 copiedDocument.appendChild(copiedRoot);
200 return copiedDocument;