digesterを使用してXMLを解析する

7442 ワード

1、bill.xmlコンテンツ
<?xml version="1.0" encoding="GBK"?>
<document>
	<bill>
		<serialNo>20089220014</serialNo>                   <!--     -->
		<termNo>N0795</termNo>                                  <!--     -->
		<saleId>62</saleId>								    <!--            -->
		<saleName>  </saleName>			<!--      -->

		<buyId>74</buyId>							        <!--            -->
		<buyName>  </buyName>			  <!--      -->
		
		<totalWeight>40</totalWeight>                          <!--     (  ) -->
		<totalMoney>220</totalMoney>                           <!--     ( )-->
		<saleDate>2008-8-18 00:00:00</saleDate>                 <!--      -->
		<status>0</status>                                      <!--      -1:   0/'':   -->
		
		<billItem>
			<variety>   </variety>								<!--     -->
			<weight>10</weight>									<!--   (  ) -->
			<price>5</price>									<!--   ( /  ) -->
			<total>50</total>									<!--    ( ) -->
		</billItem>

		<billItem>
			<variety>   </variety>								<!--     -->
			<weight>10</weight>									<!--   (  ) -->
			<price>6</price>									<!--   ( /  ) -->
			<total>60</total>									<!--    ( ) -->
		</billItem>
		
		<billItem>
			<variety>  </variety>								<!--     -->
			<weight>10</weight>									<!--   (  ) -->
			<price>5</price>									<!--   ( /  ) -->
			<total>50</total>									<!--    ( ) -->
		</billItem>
		
		<billItem>
			<variety>   </variety>								<!--     -->
			<weight>10</weight>									<!--   (  ) -->
			<price>6</price>									<!--   ( /  ) -->
			<total>60</total>									<!--    ( ) -->
		</billItem>
	</bill>
</document>

2、xmlのクラスを解析する
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;

import org.apache.commons.digester.Digester;

import com.data.bill.entity.Bill;
import com.data.bill.entity.BillItem;
import com.util.DateHelper;


public class BillDigest {
	private Bill bill;

	public Bill getBill() {
		return bill;
	}

	private void initBill() {
		if (bill == null) {
			bill = new Bill();
		}
	}
	
	public void addBill(
			String serialNo, 
			String termNo, 
			String saleId, 
			String saleName, 
			String buyId, 
			String buyName,
			String totalWeight, 
			String totalMoney, 
			String saleDate, 
			String status) {
		initBill();
		bill.setSerialNo(stringToEmpty(serialNo));
		bill.setTermNo(stringToEmpty(termNo));
		bill.setSaleId(integerToEmpty(saleId));
		bill.setSaleName(stringToEmpty(saleName));
		bill.setBuyId(integerToEmpty(buyId));
		bill.setBuyName(stringToEmpty(buyName));

		bill.setTotalWeight(doubleToEmpty(totalWeight));
		bill.setTotalMoney(doubleToEmpty(totalMoney));
		bill.setSaleDate(DateHelper.parseDate(saleDate));
		bill.setStatus(integerToEmpty(status));
	}
	
	public void addBillItem(
			String variety, 
			String weight, 
			String price, 
			String total){
		initBill();
		BillItem item = new BillItem();
		item.setVariety(stringToEmpty(variety));
		item.setWeight(doubleToEmpty(weight));
		item.setPrice(doubleToEmpty(price));
		item.setTotal(doubleToEmpty(total));
		item.setHeader(bill);
		bill.getItems().add(item);
	}
	
	public static Bill getBill(File xmlFile) {
		BufferedReader reader = null;
		Bill bill = null;
		String s;
		StringBuffer buffer = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(xmlFile));
			while((s = reader.readLine()) != null) {
				buffer.append(s);
			}
			bill = getBill(buffer.toString());
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
			bill = null;
		}
		return bill;
	}
	
	public static Bill getBill(InputStream is) {
		if (is == null) {
			return null;
		}
		
		BufferedReader reader = null;
		Bill bill = null;
		String s;
		StringBuffer buffer = new StringBuffer();
				
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			while ((s = reader.readLine()) != null) {
				buffer.append(s);
			}
			bill = getBill(buffer.toString());
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
			bill = null;
		}
		
		return bill;
	}

	public static Bill getBill(String xml) {
		
		///StringBuffer buffer = new StringBuffer(xml);
		/*Pattern p = Pattern.compile("<[^>]*?>");
		Matcher m = p.matcher(buffer);
		while(m.find()) {
			buffer.replace(m.start(), m.end(), xml.substring(m.start(),m.end()).toLowerCase());
		}*/
		String parseXML = xml;
		
		Bill bill = null;
		BillDigest helper;
		//    digester。      commons-logging.jar、commons-collections.jar、commons-beanutils.jar
		Digester digester = new Digester();
		//   XML       DTD(Document type definition)  
		digester.setValidating(false);
		//    document      ,    BillDigest  
		digester.addObjectCreate("document", BillDigest.class);
		//    document/bill      ,  addBill      , 10   
		digester.addCallMethod("document/bill", "addBill", 10);
		//    document/bill/*      ,    
		digester.addCallParam("document/bill/serialNo", 0);
		digester.addCallParam("document/bill/termNo", 1);
		digester.addCallParam("document/bill/saleId", 2);
		digester.addCallParam("document/bill/saleName", 3);
		digester.addCallParam("document/bill/buyId", 4);
		digester.addCallParam("document/bill/buyName", 5);
		digester.addCallParam("document/bill/totalWeight", 6);
		digester.addCallParam("document/bill/totalMoney", 7);
		digester.addCallParam("document/bill/saleDate", 8);
		digester.addCallParam("document/bill/status", 9);
		
		//    document/bill/billItem      ,  addBillItem      , 4   
		digester.addCallMethod("document/bill/billItem", "addBillItem", 4);
		//    document/bill/billItem/*      ,    
		digester.addCallParam("document/bill/billItem/variety", 0);
		digester.addCallParam("document/bill/billItem/weight", 1);
		digester.addCallParam("document/bill/billItem/price", 2);
		digester.addCallParam("document/bill/billItem/total", 3);
		
		try {
			// digester       
			helper = (BillDigest)digester.parse(new StringReader(parseXML));
			bill = helper.getBill();
		}catch (Exception e) {
			e.printStackTrace();
			bill = null;
		}
		return bill;
	}
	
	public static String stringToEmpty(String obj)
	{
		if(obj==null){
			return "";
		}else{
			return obj;
		}
	}
	
	public static Integer integerToEmpty(String obj)
	{
		if(obj==null){
			return new Integer(0);
		}else{
			return Integer.valueOf(obj);
		}
	}
	
	public static Double doubleToEmpty(String obj)
	{
		if(obj==null){
			return new Double(0);
		}else{
			return Double.valueOf(obj);
		}
	}
}

 
まとめ:呼び出し
public static Bill getBill(File xmlFile)、public static Bill getBill(InputStreams)、public static Bill getBill(String xml)は、異なるパラメータを入力してBillオブジェクトを返します.