Tuesday, May 04, 2010

StudyNote--IV DML--JAVA SAX XML

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
import java.util.regex.*;
<copyright(c) by sksc.me>
<No one can just copy and paste these codes without permission by sksc.me before 1st June 2010>
public class SAXPrint extends DefaultHandler{
   private int indent=0;
   private int CountStart=0;
   private int CountEnd=0;
   public void PrintIndent(){
  for(int i=0;i<indent;i++){
  System.out.print("|");
  }
   }
   public void startDocument() throws SAXException{
/*Here comes to a basic question.Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.* /
  System.out.println("Orders.xml");
   }
   public void startElement(String NameSpaceURI,String LocalName,String QName,Attributes attrs)throws SAXException{
          CountStart++;
  CountEnd=0;
  if(CountStart>=2){
  System.out.print("\n");
  }
   PrintIndent();
System.out.print("+-"+QName);
  if(attrs.getValue(0)!=null){
  System.out.print("  (");
  for(int i=0;i<attrs.getLength();i++){
  System.out.print(" "+attrs.getQName(i)+"="+attrs.getValue(i));
  if(i!=attrs.getLength()-1){System.out.print(",");}
  }
  System.out.print(" )");
  }
  indent++;
   }
   public void characters(char ch[], int start, int length) throws SAXException{
String data=new String(ch,start,length);
Pattern  p= Pattern.compile("\\S+?\\s");
/*This is to use java pattern match to find the long string where there is at least a whitespace inside, and only extract the first word.\\S means all kind of characters while ? means non-greedy,and \\s is representing whitespace*/
    Matcher match = p.matcher(data);
    if(match.find(0)) {
/*match.find(0) is the first word that matches the pattern,that is all what we need,enough.*/
        String MatchWord = match.group().trim();
        System.out.print(":"+MatchWord+"...");
    }else  if(!data.trim().equals(""))
       System.out.print(":"+data.trim());
/*This function returns a string with leading and trailing whitespace omitted*/
      }
   }
   public void endElement(String NameSpaceURI,String LocalName,String QName) throws SAXException{
indent--; CountStart=0; CountEnd++; if(CountEnd>=2){ System.out.print(""); }else{System.out.println();} }
   public void endDocument() throws SAXException{
   }
    public static String FileCheck(String arg) throws IOException{
  Pattern  pattern= Pattern.compile("\\S+?\\.xml");
  Matcher matcher = pattern.matcher(arg);
  if(!matcher.find()){
  System.out.println("Wrong FileExtension");
  System.exit(0);
  }
  else if(!(new File(arg)).exists()){
  System.out.println("The File Does Not Exist");
  System.exit(0);
  }
return arg;
   }
   public static void main(String arg[]) throws SAXException, IOException, ParserConfigurationException{
          if(arg.length==0){
  System.out.println("No FileName Input");
  System.exit(0);
  }
  String FileName=FileCheck(arg[0]);
  XMLReader xmlReader=XMLReaderFactory.createXMLReader();
  xmlReader.setContentHandler(new SAXPrint());
  xmlReader.parse(new InputSource(FileName));
/*This is one of  the way to read  XML file to memory.There are three ways to set up a SAX  Parser
(1)XMLReader reader=XMLReaderFactory.createXMLReader();//This is what I am using
(2)XMLReader reader=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
To code in this way,one should have had a certain class org.apache.xerces.parsers.SAXParser in class path and imported it.Otherwise it will throw a java.lang.ClassNotFoundException;
(3)DefaultHandler handler = new SAXPrint(); // Use the default (non-validating) parser
  SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidting(true);
/*Non-validating can be used if the file is well-formed,it works without regard to the actual content.On the other hand,a validating parser reads the DOCTYPE declaration and retrieves a file of definitions called DTD for the data.File can also be described with XML schema,but the syntax is different*/
try {
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(new File("orders.xml"), handler ); 
  } catch (Throwable t) {
    t.printStackTrace();
  }
*/
}
}

Labels: , , ,