Hi,
 
I am trying to XML serializer to format a XML file that I frequently change. I want to keep everything in the original document there (e.g. comment), just use the XML serializer to format the document. I found that using DefaultHandler2 has a comment callback, however, it seems that it didn't work, since i didn't see anything is printed in that method. Other than that, if I get the comment() call back, how can I make the ContentHandler to write the comment into output stream. Any hint would be appreciated.
 
Steve.
 
My code is like:
 

package xml;

import java.io.FileOutputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
//import org.xml.sax.helpers.DefaultHandler ;
import org.xml.sax.ext.DefaultHandler2;

/**
 * A writer which parses XML file and output it as standard indented format
 * @author lingzhi.zhang
 *
 */
public class XercesXMLWriter extends DefaultHandler2

 private static ContentHandler hd;
 public static void main(String[] args)
 {
  if(args.length != 1)
  {
   System.err.println("Usage: cmd filename");
            System.exit(1);
  }

  // initialize and start Serialization
  try
  {
   FileOutputStream fos = new FileOutputStream(args[0] + ".new");
   OutputFormat of = new OutputFormat("XML","UTF-8",true);
   of.setIndent(1);
   of.setIndenting(true);
//   of.setDoctype(null,"users.dtd");
   XMLSerializer serializer = new XMLSerializer(fos,of);
   hd = serializer.asContentHandler();
  } catch (Throwable t) {
   t.printStackTrace();
  }
  
  // initialize and start parser
  try
  {
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser parser = factory.newSAXParser();
      DefaultHandler2 handler = new XercesXMLWriter();
      parser.parse(args[0], handler);
  }
  catch (Throwable t)
  {
   t.printStackTrace();
  }
  System.exit(0);
 }

 public void startDocument() throws SAXException
 {
  hd.startDocument();
 }
 
 public void startElement(String namespaceURI,
                String lName, // local name
                String qName, // qualified name
                Attributes attrs)
 throws SAXException
 {
  hd.startElement(namespaceURI, lName, qName, attrs);
 }
 
 public void character(char buf[], int offset, int len)
 throws SAXException
 {
  hd.characters(buf, offset, len);
 }
 
 public void endElement(String namespaceURI,
       String sName, // simple name
       String qName  // qualified name
             )
 throws SAXException
 {
  hd.endElement(namespaceURI, sName, qName);
 }

 public void endDocument() throws SAXException
 {
  hd.endDocument();
 }
 
 public void comment(char[] ch, int start, int length)
 throws SAXException
 {
  System.out.println("comment");
 }
}

Reply via email to