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 org.w3c.dom.Document;
13 import org.w3c.dom.Element;
14 import org.w3c.dom.Node;
15 import org.xml.sax.SAXException;
17 import javax.xml.XMLConstants;
18 import javax.xml.namespace.QName;
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.Source;
24 import javax.xml.transform.Transformer;
25 import javax.xml.transform.TransformerException;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.TransformerFactoryConfigurationError;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import javax.xml.transform.stream.StreamSource;
31 import javax.xml.validation.Schema;
32 import javax.xml.validation.SchemaFactory;
33 import javax.xml.xpath.XPathExpression;
34 import javax.xml.xpath.XPathExpressionException;
35 import java.io.ByteArrayInputStream;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.StringWriter;
42 public class XmlUtil {
44 public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
46 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
47 Document doc = readXmlToDocument(xmlContent);
48 return doc.getDocumentElement();
51 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
52 Document doc = readXmlToDocument(xmlContent);
53 return doc.getDocumentElement();
56 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
57 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
60 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
61 DocumentBuilderFactory factory = getDocumentBuilderFactory();
62 DocumentBuilder dBuilder;
64 dBuilder = factory.newDocumentBuilder();
65 } catch (ParserConfigurationException e) {
66 throw new RuntimeException(e);
68 Document doc = dBuilder.parse(xmlContent);
70 doc.getDocumentElement().normalize();
74 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
75 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
78 private static final DocumentBuilderFactory getDocumentBuilderFactory() {
79 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
80 factory.setNamespaceAware(true);
81 factory.setCoalescing(true);
82 // factory.setValidating(true);
83 factory.setIgnoringElementContentWhitespace(true);
84 factory.setIgnoringComments(true);
88 public static Document newDocument() {
89 DocumentBuilderFactory factory = getDocumentBuilderFactory();
91 DocumentBuilder builder = factory.newDocumentBuilder();
92 Document document = builder.newDocument();
94 } catch (ParserConfigurationException e) {
95 throw new RuntimeException(e);
99 public static Element createTextElement(Document document, String name, String content) {
100 Element typeElement = document.createElement(name);
101 typeElement.appendChild(document.createTextNode(content));
105 public static void addNamespaceAttr(Element root, String namespace) {
106 root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
109 public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
110 root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
113 public static Element createPrefixedTextElement(Document document, String key, String prefix, String moduleName) {
114 return createTextElement(document, key, concat(prefix, moduleName));
117 private static String concat(String prefix, String value) {
118 return prefix + ":" + value;
121 public static String toString(Document document) {
122 return toString(document.getDocumentElement());
125 public static String toString(Element xml) {
126 return toString(xml, false);
129 public static String toString(XmlElement xmlElement) {
130 return toString(xmlElement.getDomElement(), false);
133 public static String toString(Element xml, boolean addXmlDeclaration) {
135 Transformer transformer = TransformerFactory.newInstance().newTransformer();
136 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
137 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
139 StreamResult result = new StreamResult(new StringWriter());
140 DOMSource source = new DOMSource(xml);
141 transformer.transform(source, result);
143 String xmlString = result.getWriter().toString();
145 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
146 throw new RuntimeException("Unable to serialize xml element " + xml, e);
150 public static String toString(Document doc, boolean addXmlDeclaration) {
151 return toString(doc.getDocumentElement(), addXmlDeclaration);
154 public static Schema loadSchema(InputStream... fromStreams) {
155 Source[] sources = new Source[fromStreams.length];
157 for (InputStream stream : fromStreams) {
158 sources[i++] = new StreamSource(stream);
161 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
163 return schemaFactory.newSchema(sources);
164 } catch (SAXException e) {
165 throw new IllegalStateException("Failed to instantiate XML schema", e);
169 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
171 return expr.evaluate(rootNode, returnType);
172 } catch (XPathExpressionException e) {
173 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
177 public static Document createDocumentCopy(Document original) {
178 final Document copiedDocument = newDocument();
179 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
180 copiedDocument.appendChild(copiedRoot);
181 return copiedDocument;