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;
13 import javax.xml.XMLConstants;
14 import javax.xml.namespace.QName;
15 import javax.xml.parsers.DocumentBuilder;
16 import javax.xml.parsers.DocumentBuilderFactory;
17 import javax.xml.parsers.ParserConfigurationException;
18 import javax.xml.transform.*;
19 import javax.xml.transform.dom.DOMSource;
20 import javax.xml.transform.stream.StreamResult;
21 import javax.xml.transform.stream.StreamSource;
22 import javax.xml.validation.Schema;
23 import javax.xml.validation.SchemaFactory;
24 import javax.xml.xpath.XPathExpression;
25 import javax.xml.xpath.XPathExpressionException;
27 import org.w3c.dom.Document;
28 import org.w3c.dom.Element;
29 import org.w3c.dom.Node;
30 import org.xml.sax.SAXException;
32 import com.google.common.base.Charsets;
34 public class XmlUtil {
36 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
38 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
39 Document doc = readXmlToDocument(xmlContent);
40 return doc.getDocumentElement();
43 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
44 Document doc = readXmlToDocument(xmlContent);
45 return doc.getDocumentElement();
48 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
49 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
52 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
53 DocumentBuilderFactory factory = getDocumentBuilderFactory();
54 DocumentBuilder dBuilder;
56 dBuilder = factory.newDocumentBuilder();
57 } catch (ParserConfigurationException e) {
58 throw new RuntimeException(e);
60 Document doc = dBuilder.parse(xmlContent);
62 doc.getDocumentElement().normalize();
66 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
67 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
70 private static final DocumentBuilderFactory getDocumentBuilderFactory() {
71 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
72 factory.setNamespaceAware(true);
73 factory.setCoalescing(true);
74 // factory.setValidating(true);
75 factory.setIgnoringElementContentWhitespace(true);
76 factory.setIgnoringComments(true);
80 public static Document newDocument() {
81 DocumentBuilderFactory factory = getDocumentBuilderFactory();
83 DocumentBuilder builder = factory.newDocumentBuilder();
84 Document document = builder.newDocument();
86 } catch (ParserConfigurationException e) {
87 throw new RuntimeException(e);
91 public static Element createTextElement(Document document, String name, String content) {
92 Element typeElement = document.createElement(name);
93 typeElement.appendChild(document.createTextNode(content));
97 public static void addNamespaceAttr(Element root, String namespace) {
98 root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
101 public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
102 root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
105 public static Element createPrefixedTextElement(Document document, String key, String prefix, String moduleName) {
106 return createTextElement(document, key, concat(prefix, moduleName));
109 private static String concat(String prefix, String value) {
110 return prefix + ":" + value;
113 public static String toString(Document document) {
114 return toString(document.getDocumentElement());
117 public static String toString(Element xml) {
118 return toString(xml, false);
121 public static String toString(XmlElement xmlElement) {
122 return toString(xmlElement.getDomElement(), false);
125 public static String toString(Element xml, boolean addXmlDeclaration) {
127 Transformer transformer = TransformerFactory.newInstance().newTransformer();
128 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
129 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
131 StreamResult result = new StreamResult(new StringWriter());
132 DOMSource source = new DOMSource(xml);
133 transformer.transform(source, result);
135 String xmlString = result.getWriter().toString();
137 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
138 throw new RuntimeException("Unable to serialize xml element " + xml, e);
142 public static String toString(Document doc, boolean addXmlDeclaration) {
143 return toString(doc.getDocumentElement(), addXmlDeclaration);
146 public static Schema loadSchema(InputStream... fromStreams) {
147 Source[] sources = new Source[fromStreams.length];
149 for (InputStream stream : fromStreams) {
150 sources[i++] = new StreamSource(stream);
153 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
155 return schemaFactory.newSchema(sources);
156 } catch (SAXException e) {
157 throw new IllegalStateException("Failed to instantiate XML schema", e);
161 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
163 return expr.evaluate(rootNode, returnType);
164 } catch (XPathExpressionException e) {
165 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
169 public static Document createDocumentCopy(Document original) {
170 final Document copiedDocument = newDocument();
171 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
172 copiedDocument.appendChild(copiedRoot);
173 return copiedDocument;