OASIS Mailing List ArchivesView the OASIS mailing list archive below
or browse/search using MarkMail.

 


Help: OASIS Mailing Lists Help | MarkMail Help

 


 

   A solution to get SAX InputSource from a DOM Document

[ Lists Home | Date Index | Thread Index ]

 
Sometimes you need a SAX InputSource from a DOM Document object. For example, if you are using SAX parser to map XML to Java objects, but your source is a DOM Document object.
 
Here is a solution I found, in which the only problem is that it throws a RuntimeException when the transfromation fails:
 
 
public InputStream convert(org.w3c.dom.Document edoc) throws IOException {
 
        final org.w3c.dom.Document doc = edoc;
        final PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream();
        pis.connect(pos);
 
        (new Thread(new Runnable() {
 
            public void run() {
                try {
                    transform(doc, pos);
                }
                catch (TransformerException _ex) {
                    throw new RuntimeException("Failed to tranform org.w3c.dom.Document to PipedOutputStream", _ex);
                }
                finally {
                    try {
                        pos.close();
                    }
                    catch (IOException e) {
 
                    }
                }
            }
        }, "MyClassName.convert(org.w3c.dom.Document edoc)")).start();
 
        return pis;
    }
 
 
 private void transform(org.w3c.dom.Document edoc, PipedOutputStream pos) throws TransformerException {
 
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
 
            transformer.setOutputProperty("encoding", "ISO-8859-1");
            transformer.setOutputProperty("indent", "yes");
 
            transformer.transform(new DOMSource(edoc), new StreamResult(pos));
 
}
 
 
 

Best regards,
 

--
Albert Yu
( Yu Yizhuan )
Software Engineer




 

News | XML in Industry | Calendar | XML Registry
Marketplace | Resources | MyXML.org | Sponsors | Privacy Statement

Copyright 2001 XML.org. This site is hosted by OASIS