`
gcgmh
  • 浏览: 349939 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

xml文件解析之sax解析

阅读更多
package org.itfuture.netoa.admin;

  import java.io.FileInputStream;
  import java.io.FileReader;

  import org.xml.sax.*;
  import org.xml.sax.InputSource;
  import org.xml.sax.XMLReader;//解析器
  import org.xml.sax.helpers.DefaultHandler; //确省的拦截句柄 
  import org.xml.sax.helpers.XMLReaderFactory;
  import java.io.InputStreamReader;

  
  
 //该类来充当拦截器 
public class SAXSampleO1 extends DefaultHandler {
	
	public SAXSampleO1() {
		
	}
	
    //该方法负责拦截starDocument相应解析事件
	public void startDocument() throws SAXException 
	{
		System.out.println("[开始xml解析:]");
	}
	
	public void startElement(String namespaceUri, String ename, String qname, Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("[解析的元素为:]"+ename);
		if(ename.equals("account")){
			for(int i=0;i<attributes.getLength();i++)
			{
				String name=attributes.getLocalName(i);
				String value=attributes.getValue(i);
				
				System.out.println("该元素的属性:"+name+"---"+value);
			}
			
			
//			String type=attributes.getValue("type");
//			String number=attributes.getValue("number");
//			System.out.println("该元素的属性:type-"+type+":number-"+number);
		}
		
		
	}
	
	public void characters(char[] chars, int start, int length) throws SAXException 
	{
	    String value= new String(chars,start,length);
	    System.out.println(value);
	}


	public void endElement(String namespaceUri, String ename, String qname) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("[解析的元素结束:]"+ename);
	}


	
	public void endDocument() throws SAXException {
		System.out.println("[结束xml文档解析]");
	}
    
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
	
		 try {
			XMLReader parser=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
			parser.setContentHandler(new SAXSampleO1());;
		    //InputSource a=;
		    //parser.parse("D:/database.xml");
		    parser.parse(new InputSource(new FileReader("D:/database.xml")));
		    //parser.parse(new InputSource(new FileInputStream("D:/database.xml")));
		}catch(SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}

	}

}


package org.itfuture.netoa.admin;

import java.io.FileInputStream;
import java.io.FileReader;

import org.xml.sax.*;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;//解析器
import org.xml.sax.helpers.DefaultHandler; //确省的拦截句柄 
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.InputStreamReader;



//该类来充当拦截器 
public class SAXSample02 extends DefaultHandler {
	DBInfo info=null;
	//StringBuffer sb=new StringBuffer();//用来存读到相应元素的值
	String str="";
	public SAXSample02() 
	{
		info=new DBInfo();
	}
	
  //该方法负责拦截starDocument相应解析事件
	public void startDocument() throws SAXException 
	{
		System.out.println("[开始xml解析:]");
	}
	
	public void startElement(String namespaceUri, String ename, String qname, Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		System.out.println("[解析的元素为:]"+ename);
		if(ename.equals("account"))
		{
			for(int i=0;i<attributes.getLength();i++)
			{
				
				String name=attributes.getLocalName(i);
				String value=attributes.getValue(i);
				if(name.equals("type"))
				  info.setType(value);
				if(name.equals("number"))
				  info.setNumber(Integer.parseInt(value));
				System.out.println("该元素的属性:"+name+"---"+value);
			}	
		}
	    //sb.delete(0,sb.length());
	    str="";
	}
	
	public void characters(char[] chars, int start, int length) throws SAXException 
	{
	    String value= new String(chars,start,length);
	    System.out.println(value);
	    //sb.append(chars,start,length); 
	    str=new String(chars,start,length);
	}


	public void endElement(String namespaceUri, String ename, String qname) throws SAXException 
	{
		// TODO Auto-generated method stub
		System.out.println("[解析的元素结束:]"+ename);
		if(ename.equals("username"))
		{
		   //info.setUsername(sb.toString());	
		   info.setUsername(str);	
		}else if(ename.equals("password")){
		   //info.setPassword(sb.toString());
		   info.setPassword(str);
		}else if(ename.equals("url")){
		   //info.setUrl(sb.toString());	
		   info.setUrl(str);	
		}else if(ename.equals("driver")){
		   //info.setDriver(sb.toString());	
		   info.setDriver(str);	
		}
	}


	
	public void endDocument() throws SAXException {
		System.out.println("[结束xml文档解析]");
	}
  
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
	
		 try {
			SAXSample02 sample= new SAXSample02();
			XMLReader parser=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
			parser.setContentHandler(sample);;
		    //InputSource a=;
		    //parser.parse("D:/database.xml");
		    parser.parse(new InputSource(new FileReader("D:/database.xml")));
		    //parser.parse(new InputSource(new FileInputStream("D:/database.xml")));
            DBInfo info=sample.info;
            System.out.println(info.getType()+"--"+info.getNumber()+"---"+info.getUsername()+"---"+info.getPassword()+"--"+info.getUrl()+"---"+info.getDriver());
		}catch(SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}

	}

}


package org.itfuture.netoa.admin;
   
 import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

   
public class SAXSample03 extends DefaultHandler{
	List list=new ArrayList();
	StringBuffer sb=new StringBuffer();
    Customer cust=null;
	
	public SAXSample03() 
	{
		super();
		// TODO Auto-generated constructor stub
	}
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}
	
	public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
		// TODO Auto-generated method stub
	    if(arg1.equals("customer"))
	    {
	       cust=new Customer();	
	       list.add(cust); 
	    }
		sb.delete(0,sb.length());
	}
	
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		// TODO Auto-generated method stub
	   sb.append(arg0,arg1,arg2);
	}

	public void endElement(String arg0, String arg1, String arg2) throws SAXException {
		// TODO Auto-generated method stub
	 if(arg1.equals("FirstName"))
	 {	
	    cust.setFirstname(sb.toString());	 
	 }else if(arg2.equals("LastName")){
		cust.setLasetname(sb.toString());
	 }else if(arg2.equals("CustId")){
        cust.setCustid(sb.toString()); 
	 }
	}

	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		try {
			XMLReader xr=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		    SAXSample03 sample=new SAXSample03();
		    xr.setContentHandler(sample);
		    xr.parse(new InputSource(new FileInputStream("D:/Example3.xml")));
		    List list=sample.list;
		    for(int i=0;i<list.size();i++)
		    {
		      Customer one=	(Customer)list.get(i);
		      System.out.println(one.getCustid()+"---"+one.getFirstname()+"---"+one.getLasetname());
		    }
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			 e.printStackTrace();
		}
		

	}

}

package org.itfuture.netoa.admin;

import java.io.CharArrayWriter;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class SAXSample04 extends DefaultHandler {
    private List custlist=new ArrayList();
	private List orderlist=new ArrayList();
	StringBuffer sb=new StringBuffer();
	CharArrayWriter caw=new CharArrayWriter();
	Customer cust=null;
	OrderItem item=null;
	
	
	
	public SAXSample04() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}

	public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
		if(arg1.equals("Customer"))
		{
		   cust=new Customer();
		   custlist.add(cust);
		}else if(arg1.equals("OrderItem")){
		   item=new OrderItem();
		   item.setCustid(cust.getCustid());
		   orderlist.add(item);
		}
		//sb.delete(0,sb.length());
		caw.reset();
		
	}
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
	   //sb.append(arg0,arg1,arg2);
		caw.write(arg0,arg1,arg2);
	}

	public void endElement(String arg0, String arg1, String arg2) throws SAXException {
		if(arg1.equals("FirstName")){
			cust.setFirstname(caw.toString());
			//cust.setFirstname(sb.toString());
		}else if(arg1.equals("LastName")){
			//cust.setLasetname(sb.toString());
			cust.setLasetname(caw.toString());
		}else if(arg1.equals("CustId")){
			//cust.setCustid(sb.toString());
			cust.setCustid(caw.toString());
		}
		if(arg1.equals("ProductCode")){
			item.setProductcode(caw.toString());
			//item.setProductcode(sb.toString());
		}else if(arg1.equals("Quantity")){
			item.setQuantity(Integer.parseInt(caw.toString().trim()));
			//item.setQuantity(Integer.parseInt(sb.toString().trim()));
		}else if(arg1.equals("Price")){
			item.setPrice(Double.parseDouble(caw.toString().trim()));
			//item.setPrice(Double.parseDouble(sb.toString().trim()));
		}else if(arg1.equals("Description")){
			item.setDescription(caw.toString());
			//item.setDescription(sb.toString());
			
		}
		
		
	}
	
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception 
	{
	  SAXSample04 sample=new SAXSample04();
      XMLReader parse=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
      parse.setContentHandler(sample);
      parse.parse(new InputSource(new FileReader("D:/Example4.xml")));
      List custlist=sample.custlist;
      List orderlist=sample.orderlist;
      for(int i=0;i<custlist.size();i++)
      {
    	 Customer cust=(Customer)custlist.get(i); 
    	 cust.print(System.out);
      }
      for(int i=0;i<orderlist.size();i++)
      {
    	  OrderItem  item=(OrderItem)orderlist.get(i);
          item.print(System.out);
      }
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics