1 16 17 package info.jtrac.util; 18 19 import java.io.IOException ; 20 import java.io.StringWriter ; 21 import javax.xml.transform.Transformer ; 22 import javax.xml.transform.TransformerFactory ; 23 24 import org.dom4j.Document; 25 import org.dom4j.DocumentException; 26 import org.dom4j.DocumentHelper; 27 import org.dom4j.Element; 28 import org.dom4j.io.DocumentResult; 29 import org.dom4j.io.DocumentSource; 30 import org.dom4j.io.OutputFormat; 31 import org.dom4j.io.XMLWriter; 32 33 36 public final class XmlUtils { 37 38 42 public static String getAsPrettyXml(String xmlString) { 43 return getAsPrettyXml(parse(xmlString)); 44 } 45 46 50 public static String getAsPrettyXml(Document document) { 51 OutputFormat format = new OutputFormat(" ", true); 52 format.setSuppressDeclaration(true); 53 StringWriter out = new StringWriter (); 54 XMLWriter writer = new XMLWriter(out, format); 55 try { 56 try { 57 writer.write(document); 58 } finally { 59 writer.close(); 60 } 61 } catch (IOException ioe) { 62 throw new RuntimeException (ioe); 63 } 64 return out.toString().trim(); 65 } 66 67 71 public static Document parse(String xmlString) { 72 try { 73 return DocumentHelper.parseText(xmlString); 74 } catch (DocumentException de) { 75 throw new RuntimeException (de); 76 } 77 } 78 79 public static Element getNewElement(String name) { 80 return DocumentHelper.createElement(name); 81 } 82 83 public static Document getNewDocument(String rootElementName) { 84 Document d = DocumentHelper.createDocument(); 85 d.addElement(rootElementName); 86 return d; 87 } 88 89 public static Document transform(Document source, Document stylesheet) { 90 TransformerFactory factory = TransformerFactory.newInstance(); 91 try { 92 Transformer transformer = factory.newTransformer(new DocumentSource(stylesheet)); 93 DocumentResult result = new DocumentResult(); 94 transformer.transform(new DocumentSource(source), result ); 95 return result.getDocument(); 96 } catch (Exception e) { 97 throw new RuntimeException (e); 98 } 99 } 100 101 } 102 | Popular Tags |