This tip shows you how to use the LSOutput/LSSerializer interfaces (from the DOM Load and Save API) for serialize a DOM tree. Extract the DOM tree with the following basic steps:
//AirWings_xml.xml - the XML document from this example//LSOutput_1.xml - the result of serializationimport javax.xml.parsers.*;import org.w3c.dom.*;import java.io.*;import org.w3c.dom.ls.*;class DOM{ DocumentBuilderFactory DBF=null; DocumentBuilder DB=null; Document D=null; DOMImplementationLS DOMiLS=null; FileOutputStream FOS=null; public DOM(){} public void StartSerialization(String XMLdoc) { try{ //create a DocumentBuilderFactory object DBF=DocumentBuilderFactory.newInstance(); //create a DocumentBuilder object DB=DBF.newDocumentBuilder(); //get the DOM tree D=DB.parse(new File(XMLdoc)); }catch(javax.xml.parsers.ParserConfigurationException e) {System.out.println(e.getMessage()); }catch(org.xml.sax.SAXException e) {System.out.println(e.getMessage()); }catch(java.io.IOException e) {System.out.println(e.getMessage());} //testing the support for DOM Load and Save if((D.getFeature("Core","3.0")!=null)&& (D.getFeature("LS","3.0")!=null)) { DOMiLS=(DOMImplementationLS)(D.getImplementation()). getFeature("LS","3.0"); System.out.println("[Using DOM Load and Save]"); }else { System.out.println("[DOM Load and Save unsupported]"); System.exit(0); } //get a LSOutput object LSOutput LSO=DOMiLS.createLSOutput(); //setting the location for storing the result of serialization try{ FOS=new FileOutputStream( "C://Data_Local//xml//docs//LS_output_1.xml"); LSO.setByteStream((OutputStream)FOS); }catch(java.io.FileNotFoundException e) {System.err.println(e.getMessage());} //get a LSSerializer object LSSerializer LSS=DOMiLS.createLSSerializer(); //do the serialization boolean ser=LSS.write(D,LSO); //publish the result if(ser) System.out.println("[Serialization done!]"); else System.out.println("[Serialization failed!]"); try{ FOS.close(); }catch(java.io.IOException e) {System.out.println(e.getMessage());} } }public class serializationExample{ public static void main(String[] args) { DOM t=new DOM(); t.StartSerialization("C://Data_Local//xml//docs//AirWings_xml.xml"); }}