001/** 002 * 003 * Copyright 2017-2018 Florian Schmaus. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.util; 018 019import java.io.StringReader; 020import java.io.StringWriter; 021import java.util.logging.Level; 022import java.util.logging.Logger; 023 024import javax.xml.transform.OutputKeys; 025import javax.xml.transform.Transformer; 026import javax.xml.transform.TransformerException; 027import javax.xml.transform.TransformerFactory; 028import javax.xml.transform.stream.StreamResult; 029import javax.xml.transform.stream.StreamSource; 030 031public class XmlUtil { 032 033 private static final Logger LOGGER = Logger.getLogger(XmlUtil.class.getName()); 034 035 private static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); 036 037 static { 038 try { 039 transformerFactory.setAttribute("indent-number", 2); 040 } catch (IllegalArgumentException e) { 041 LOGGER.log(Level.INFO, "XML TransformerFactory does not support indent-number attribute", e); 042 } 043 } 044 045 public static String prettyFormatXml(CharSequence xml) { 046 String xmlString = xml.toString(); 047 StreamSource source = new StreamSource(new StringReader(xmlString)); 048 StringWriter stringWriter = new StringWriter(); 049 StreamResult result = new StreamResult(stringWriter); 050 051 try { 052 Transformer transformer = transformerFactory.newTransformer(); 053 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 054 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 055 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 056 057 // Transform the requested string into a nice formatted XML string 058 transformer.transform(source, result); 059 } 060 catch (TransformerException | IllegalArgumentException e) { 061 LOGGER.log(Level.SEVERE, "Transformer error", e); 062 return xmlString; 063 } 064 065 return stringWriter.toString(); 066 } 067}