1 9 10 package org.dom4j.samples.jaxp; 11 12 import org.dom4j.samples.SAXDemo; 13 14 import java.io.Reader ; 15 import java.io.StringReader ; 16 import java.io.StringWriter ; 17 import java.io.Writer ; 18 19 import javax.xml.transform.Transformer ; 20 import javax.xml.transform.TransformerFactory ; 21 import javax.xml.transform.stream.StreamResult ; 22 import javax.xml.transform.stream.StreamSource ; 23 24 import org.dom4j.Document; 25 import org.dom4j.io.DocumentResult; 26 import org.dom4j.io.DocumentSource; 27 import org.dom4j.io.XMLWriter; 28 29 36 public class RoundTripDemo extends SAXDemo { 37 38 public static void main(String [] args) { 39 run(new RoundTripDemo(), args); 40 } 41 42 public RoundTripDemo() { 43 } 44 45 protected void outputDocument(Document document, Writer out) { 46 try { 47 TransformerFactory factory = TransformerFactory.newInstance(); 48 49 Transformer transformer = factory.newTransformer(); 50 51 StreamResult result = new StreamResult (out); 52 DocumentSource source = new DocumentSource(document); 53 54 transformer.transform(source, result); 55 } catch (Exception ex) { 56 ex.printStackTrace(); 57 } 58 59 } 60 61 protected Document parseDocument(Reader in) { 62 try { 63 TransformerFactory factory = TransformerFactory.newInstance(); 64 65 Transformer transformer = factory.newTransformer(); 66 67 DocumentResult result = new DocumentResult(); 68 StreamSource source = new StreamSource (in); 69 70 transformer.transform(source, result); 71 72 return result.getDocument(); 73 } catch (Exception ex) { 74 ex.printStackTrace(); 75 return null; 76 } 77 78 } 79 80 81 protected void process(Document document) throws Exception { 82 83 System.out.println("about to output: " + document); 84 85 StringWriter out = new StringWriter (); 86 outputDocument(document, out); 87 88 Document doc2 = parseDocument(new StringReader (out.toString())); 89 90 System.out.println("parsed back again: " + doc2); 91 92 System.out.println("Writing it out..."); 93 94 XMLWriter writer = new XMLWriter(System.out); 95 writer.write(doc2); 96 97 } 98 } 99 100 138 | Popular Tags |