Use Xerces-J to Obtain a Serialized DOM Tree

Suppose you need to serialize a DOM tree, with the result being an XML document. Xerces-J allows you to specify a maximum line length and an indent value. Here’s an example:

//the XML document used in this example is://"C://Data_local//xml//docs//AirWings_xml.xml"//The application has two steps:// 1. - Get the DOM tree of this XML document;// 2. - Serialize the DOM by using Xerces-J;// Notice that the indentation is set to 5 characters and the maximum //line length to 100 characters.import javax.xml.parsers.*;import org.w3c.dom.*;import*;import org.apache.xml.serialize.*;class DOM{    DocumentBuilderFactory DBF=null;    DocumentBuilder DB=null;    Document D=null;    FileOutputStream FOS=null;    public DOM(){}     //get the DOM    public void createDOMTree(String XMLdoc)    {    try{                  System.setProperty("javax.xml.parsers.DocumentBuilderFactory",                                               "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");    //get a DocumentBuilderFactory object    DBF=DocumentBuilderFactory.newInstance();           //get a DocumentBuilder object    DB=DBF.newDocumentBuilder();           //get the DOM tree from the XML document    D=DB.parse(new File(XMLdoc));                         //get a OutputFormat object    OutputFormat OF=new OutputFormat();           //setting indentation and maximum line length    OF.setIndent(5);    OF.setLineWidth(100);           //get an OutputStream object    try{       FOS=new FileOutputStream         ("C://Data_Local//xml//docs//SerXerces.xml");       }catch( e)          {System.err.println(e.getMessage());}          //configure an XMLSerializer object    XMLSerializer XMLS=new XMLSerializer();    XMLS.setOutputFormat(OF);    XMLS.setOutputByteStream((OutputStream)FOS);          //start serialization    XMLS.serialize(D);    }catch(javax.xml.parsers.ParserConfigurationException e)       {System.out.println(e.getMessage());    }catch(org.xml.sax.SAXException e)       {System.out.println(e.getMessage());    }catch( e)       {System.out.println(e.getMessage());}      } }public class SerializareXerces{   public static void main(String[] args)      {      DOM t=new DOM();          t.createDOMTree("C://Data_local//xml//docs//AirWings_xml.xml");      }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: