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 {
45 public static final String XMLNS_ATTRIBUTE_KEY = "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;
57 public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
58 Document doc = readXmlToDocument(xmlContent);
59 return doc.getDocumentElement();
62 public static Element readXmlToElement(InputStream xmlContent) throws SAXException, IOException {
63 Document doc = readXmlToDocument(xmlContent);
64 return doc.getDocumentElement();
67 public static Document readXmlToDocument(String xmlContent) throws SAXException, IOException {
68 return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
71 public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
72 DocumentBuilder dBuilder;
74 dBuilder = BUILDERFACTORY.newDocumentBuilder();
75 } catch (ParserConfigurationException e) {
76 throw new RuntimeException("Failed to parse XML document", e);
78 Document doc = dBuilder.parse(xmlContent);
80 doc.getDocumentElement().normalize();
84 public static Element readXmlToElement(File xmlFile) throws SAXException, IOException {
85 return readXmlToDocument(new FileInputStream(xmlFile)).getDocumentElement();
88 public static Document newDocument() {
90 DocumentBuilder builder = BUILDERFACTORY.newDocumentBuilder();
91 Document document = builder.newDocument();
93 } catch (ParserConfigurationException e) {
94 throw new RuntimeException("Failed to create document", e);
98 public static Element createTextElement(Document document, String name, String content) {
99 Element typeElement = document.createElement(name);
100 typeElement.appendChild(document.createTextNode(content));
104 public static void addNamespaceAttr(Element root, String namespace) {
105 root.setAttribute(XMLNS_ATTRIBUTE_KEY, namespace);
108 public static void addPrefixedNamespaceAttr(Element root, String prefix, String namespace) {
109 root.setAttribute(concat(XMLNS_ATTRIBUTE_KEY, prefix), namespace);
112 public static Element createPrefixedTextElement(Document document, String key, String prefix, String content) {
113 return createTextElement(document, key, concat(prefix, content));
116 private static String concat(String prefix, String value) {
117 return prefix + ":" + value;
120 public static String toString(Document document) {
121 return toString(document.getDocumentElement());
124 public static String toString(Element xml) {
125 return toString(xml, false);
128 public static String toString(XmlElement xmlElement) {
129 return toString(xmlElement.getDomElement(), false);
132 public static String toString(Element xml, boolean addXmlDeclaration) {
134 Transformer transformer = TransformerFactory.newInstance().newTransformer();
135 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
136 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
138 StreamResult result = new StreamResult(new StringWriter());
139 DOMSource source = new DOMSource(xml);
140 transformer.transform(source, result);
142 String xmlString = result.getWriter().toString();
144 } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
145 throw new RuntimeException("Unable to serialize xml element " + xml, e);
149 public static String toString(Document doc, boolean addXmlDeclaration) {
150 return toString(doc.getDocumentElement(), addXmlDeclaration);
153 public static Schema loadSchema(InputStream... fromStreams) {
154 Source[] sources = new Source[fromStreams.length];
156 for (InputStream stream : fromStreams) {
157 sources[i++] = new StreamSource(stream);
160 final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
162 return schemaFactory.newSchema(sources);
163 } catch (SAXException e) {
164 throw new IllegalStateException("Failed to instantiate XML schema", e);
168 public static Object evaluateXPath(XPathExpression expr, Object rootNode, QName returnType) {
170 return expr.evaluate(rootNode, returnType);
171 } catch (XPathExpressionException e) {
172 throw new IllegalStateException("Error while evaluating xpath expression " + expr, e);
176 public static Document createDocumentCopy(Document original) {
177 final Document copiedDocument = newDocument();
178 final Node copiedRoot = copiedDocument.importNode(original.getDocumentElement(), true);
179 copiedDocument.appendChild(copiedRoot);
180 return copiedDocument;