1 38 39 40 package samples.transform; 41 42 43 import java.io.File ; 44 import java.io.InputStream ; 45 import java.io.FileInputStream ; 46 import java.io.FileOutputStream ; 47 import java.io.BufferedInputStream ; 48 import java.io.BufferedOutputStream ; 49 import java.io.FileNotFoundException ; 50 51 import javax.xml.transform.*; 52 import javax.xml.transform.dom.*; 53 import javax.xml.transform.stream.*; 54 import javax.xml.parsers.*; 55 import org.w3c.dom.*; 56 import javax.xml.transform.sax.SAXResult ; 57 58 import javax.xml.stream.XMLStreamWriter; 59 import javax.xml.stream.XMLOutputFactory; 60 import javax.xml.stream.XMLStreamException; 61 import com.sun.xml.fastinfoset.sax.SAXDocumentSerializer; 62 63 64 65 78 public class XMLToFastInfosetSAXSerializer { 79 Transformer _transformer; 80 DocumentBuilder _docBuilder; 81 DOMSource _source = null; 82 SAXResult _result = null; 83 84 85 public XMLToFastInfosetSAXSerializer() { 86 try { 87 _transformer = TransformerFactory.newInstance().newTransformer(); 89 _docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 90 } catch (Exception e) { 91 e.printStackTrace(); 92 } 93 } 94 95 96 100 void getDOMSource(File input) { 101 try { 102 FileInputStream fis = new FileInputStream (input); 103 Document document = _docBuilder.parse(fis); 104 fis.close(); 105 _source = new DOMSource(document); 106 } 107 catch (Exception e) { 108 e.printStackTrace(); 109 } 110 111 } 112 113 117 void getSAXResult(File output) { 118 try { 119 BufferedOutputStream fos = new BufferedOutputStream (new FileOutputStream (output)); 120 SAXDocumentSerializer serializer = new SAXDocumentSerializer(); 121 serializer.setOutputStream(fos); 122 123 _result = new SAXResult (); 124 _result.setHandler(serializer); 125 _result.setLexicalHandler(serializer); 126 127 } 128 catch (Exception e) { 129 e.printStackTrace(); 130 } 131 } 132 133 138 public void write(File input, File output) { 139 getDOMSource(input); 141 getSAXResult(output); 143 144 if (_source != null && _result != null) { 145 try { 146 System.out.println("Transforming "+input.getName()+ " into " + output.getName()); 147 _transformer.transform(_source, _result); 149 } catch (Exception e) { 150 e.printStackTrace(); 151 } 152 System.out.println("\ndone."); 153 } else { 154 System.out.println("Source or Result could not be null."); 155 } 156 } 157 158 161 public static void main(String [] args) { 162 if (args.length < 1 || args.length > 4) { 163 displayUsageAndExit(); 164 } 165 166 try { 167 File input = new File (args[0]); 169 File ouput = new File (args[1]); 171 XMLToFastInfosetSAXSerializer docSerializer = new XMLToFastInfosetSAXSerializer(); 172 docSerializer.write(input, ouput); 173 } catch (Exception e) { 174 e.printStackTrace(); 175 } 176 } 177 178 private static void displayUsageAndExit() { 179 System.err.println("Usage: ant FISAXSerialixer or samples.sax.FISerializer XML_input_file FI_output_file"); 180 System.exit(1); 181 } 182 183 } 184 | Popular Tags |