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 java.io.ByteArrayInputStream;
13 import java.io.FileInputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.StringWriter;
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.TransformerException;
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;
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 import com.google.common.base.Charsets;
44 public class XmlUtil {
46 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
48 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
49 Document doc = readXmlToDocument(xmlContent);
50 return doc.getDocumentElement();
53 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
54 Document doc = readXmlToDocument(xmlContent);
55 return doc.getDocumentElement();
58 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
59 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
62 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
63 DocumentBuilderFactory factory = getDocumentBuilderFactory();
64 DocumentBuilder dBuilder;
66 dBuilder = factory.newDocumentBuilder();
67 } catch (ParserConfigurationException e) {
68 throw new RuntimeException(e);
70 Document doc = dBuilder.parse(xmlContent);
72 doc.getDocumentElement().normalize();
76 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
77 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
80 private static final DocumentBuilderFactory getDocumentBuilderFactory() {
81 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
82 factory.setNamespaceAware(true);
83 factory.setCoalescing(true);
84 factory.setIgnoringElementContentWhitespace(true);
85 factory.setIgnoringComments(true);
89 public static Document newDocument() {
90 DocumentBuilderFactory factory = getDocumentBuilderFactory();
92 DocumentBuilder builder = factory.newDocumentBuilder();
93 Document document = builder.newDocument();
95 } catch (ParserConfigurationException e) {
96 throw new RuntimeException(e);
100 public static Element createTextElement(Document document, String name, String content) {
101 Element typeElement = document.createElement(name);
102 typeElement.appendChild(document.createTextNode(content));
106 public static void addNamespaceAttr(Element root, String namespace) {
107 root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
110 public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
111 root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
114 public static Element createPrefixedTextElement(Document document, String key, String prefix, String moduleName) {
115 return createTextElement(document, key, concat(prefix, moduleName));
118 private static String concat(String prefix, String value) {
119 return prefix + ":" + value;
122 public static String toString(Document document) {
123 return toString(document.getDocumentElement());
126 public static String toString(Element xml) {
127 return toString(xml, false);
130 public static String toString(XmlElement xmlElement) {
131 return toString(xmlElement.getDomElement(), false);
134 public static String toString(Element xml, boolean addXmlDeclaration) {
136 Transformer transformer = TransformerFactory.newInstance().newTransformer();
137 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
138 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
140 StreamResult result = new StreamResult(new StringWriter());
141 DOMSource source = new DOMSource(xml);
142 transformer.transform(source, result);
144 String xmlString = result.getWriter().toString();
146 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
147 throw new RuntimeException("Unable to serialize xml element " + xml, e);
151 public static String toString(Document doc, boolean addXmlDeclaration) {
152 return toString(doc.getDocumentElement(), addXmlDeclaration);
155 public static Schema loadSchema(InputStream... fromStreams) {
156 Source[] sources = new Source[fromStreams.length];
158 for (InputStream stream : fromStreams) {
159 sources[i++] = new StreamSource(stream);
162 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
164 return schemaFactory.newSchema(sources);
165 } catch (SAXException e) {
166 throw new IllegalStateException("Failed to instantiate XML schema", e);
170 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
172 return expr.evaluate(rootNode, returnType);
173 } catch (XPathExpressionException e) {
174 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
178 public static Document createDocumentCopy(Document original) {
179 final Document copiedDocument = newDocument();
180 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
181 copiedDocument.appendChild(copiedRoot);
182 return copiedDocument;