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;
14 import java.io.ByteArrayInputStream;
16 import java.io.FileInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.StringWriter;
21 import javax.xml.XMLConstants;
22 import javax.xml.namespace.QName;
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.transform.OutputKeys;
27 import javax.xml.transform.Source;
28 import javax.xml.transform.Transformer;
29 import javax.xml.transform.TransformerFactory;
30 import javax.xml.transform.TransformerFactoryConfigurationError;
31 import javax.xml.transform.dom.DOMSource;
32 import javax.xml.transform.stream.StreamResult;
33 import javax.xml.transform.stream.StreamSource;
34 import javax.xml.validation.Schema;
35 import javax.xml.validation.SchemaFactory;
36 import javax.xml.xpath.XPathExpression;
37 import javax.xml.xpath.XPathExpressionException;
39 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
40 import org.w3c.dom.Document;
41 import org.w3c.dom.Element;
42 import org.w3c.dom.Node;
43 import org.xml.sax.SAXException;
45 public final class XmlUtil {
47 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
48 public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
49 private static final DocumentBuilderFactory BUILDERFACTORY;
52 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
53 factory.setNamespaceAware(true);
54 factory.setCoalescing(true);
55 factory.setIgnoringElementContentWhitespace(true);
56 factory.setIgnoringComments(true);
57 BUILDERFACTORY = factory;
62 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
63 Document doc = readXmlToDocument(xmlContent);
64 return doc.getDocumentElement();
67 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
68 Document doc = readXmlToDocument(xmlContent);
69 return doc.getDocumentElement();
72 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
73 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
76 // TODO improve exceptions throwing
77 // along with XmlElement
79 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
80 DocumentBuilder dBuilder;
82 dBuilder = BUILDERFACTORY.newDocumentBuilder();
83 } catch (ParserConfigurationException e) {
84 throw new IllegalStateException("Failed to parse XML document", e);
86 Document doc = dBuilder.parse(xmlContent);
88 doc.getDocumentElement().normalize();
92 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
93 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
96 public static Document newDocument() {
98 DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
99 return builder.newDocument();
100 } catch (ParserConfigurationException e) {
101 throw new IllegalStateException("Failed to create document", e);
105 public static Element createElement(final Document document, String qName, Optional<String> namespaceURI) {
106 if(namespaceURI.isPresent()) {
107 final Element element = document.createElementNS(namespaceURI.get(), qName);
108 String name = XMLNS_ATTRIBUTE_KEY;
109 if(element.getPrefix() != null) {
110 name += ":" + element.getPrefix();
112 element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
115 return document.createElement(qName);
118 public static Element createTextElement(Document document, String qName, String content, Optional<String> namespaceURI) {
119 Element typeElement = createElement(document, qName, namespaceURI);
120 typeElement.appendChild(document.createTextNode(content));
124 public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
125 String namespace, String contentWithoutPrefix) {
127 return createTextElementWithNamespacedContent(document, qName, prefix, namespace, contentWithoutPrefix, Optional.<String>absent());
130 public static Element createTextElementWithNamespacedContent(Document document, String qName, String prefix,
131 String namespace, String contentWithoutPrefix, Optional<String> namespaceURI) {
133 String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
134 Element element = createTextElement(document, qName, content, namespaceURI);
135 String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
136 element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
140 public static String createPrefixedValue(String prefix, String value) {
141 return prefix + ":" + value;
144 public static String toString(Document document) {
145 return toString(document.getDocumentElement());
148 public static String toString(Element xml) {
149 return toString(xml, false);
152 public static String toString(XmlElement xmlElement) {
153 return toString(xmlElement.getDomElement(), false);
156 public static String toString(Element xml, boolean addXmlDeclaration) {
158 Transformer transformer = TransformerFactory.newInstance().newTransformer();
159 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
160 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
162 StreamResult result = new StreamResult(new StringWriter());
163 DOMSource source = new DOMSource(xml);
164 transformer.transform(source, result);
166 return result.getWriter().toString();
167 } catch (Exception | TransformerFactoryConfigurationError e) {
168 throw new IllegalStateException("Unable to serialize xml element " + xml, e);
172 public static String toString(Document doc, boolean addXmlDeclaration) {
173 return toString(doc.getDocumentElement(), addXmlDeclaration);
176 public static Schema loadSchema(InputStream... fromStreams) {
177 Source[] sources = new Source[fromStreams.length];
179 for (InputStream stream : fromStreams) {
180 sources[i++] = new StreamSource(stream);
183 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
185 return schemaFactory.newSchema(sources);
186 } catch (SAXException e) {
187 throw new IllegalStateException("Failed to instantiate XML schema", e);
191 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
193 return expr.evaluate(rootNode, returnType);
194 } catch (XPathExpressionException e) {
195 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
199 public static Document createDocumentCopy(Document original) {
200 final Document copiedDocument = newDocument();
201 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
202 copiedDocument.appendChild(copiedRoot);
203 return copiedDocument;