sax 解析xml

前端之家收集整理的这篇文章主要介绍了sax 解析xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package org.sxj.service.product;

import java.util.ArrayList;
import java.util.List;

import org.sxj.dao.product.ProductDaoImpl;
import org.sxj.model.brand.Brand;
import org.sxj.model.product.Product;
import org.sxj.model.user.User;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Sax extends DefaultHandler {

	private List<Brand> brandList;
	private List<User> userList;
	
	private ArrayList<Product> productList;
	@Override
	public void startDocument() throws SAXException {
		productList = new ArrayList<Product>();
	}
	Product product = null;
	String tag = "";
	@Override
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
		tag = qName;
		if (qName.equals("product")) {
			product = new Product();
		}
		
	}
	
	@Override
	public void characters(char[] ch,int start,int length)
			throws SAXException {
		String data = new String(ch,start,length);
		
		if (tag.equals("productName")) {
			product.setName(data+"_");
		}
		if (tag.equals("productPrice")) {
			product.setPrice(Float.parseFloat(data)+100);
		}
		if (tag.equals("productBrand")) {
			for (Brand b : brandList) {
				if(b.getBrandName().equals(data)) {
					product.setBrand(b.getId());
				}
			}
			
			product.setName(data);
		}
		if (tag.equals("productProduceTime")) {
			product.setProduceTime(data);
		}
		if (tag.equals("productPerson")) {
			for (User productUser : userList) {
				if(productUser.getRealName().equals(data)) {
					product.setEnteringPerson(productUser.getId());
				}
			}
		}
		tag = "";
	}
		
	
	@Override
	public void endElement(String uri,String qName)
			throws SAXException {
		if (qName.equals("product")) {
			productList.add(product);
		}
	}
	
	
	
	public Sax(List<Brand> list1,List<User> list2) {
		brandList = list1;
		userList = list2;
	}
	
	@Override
	public void endDocument() throws SAXException {
		
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public List<Brand> getBrandList() {
		return brandList;
	}

	public void setBrandList(List<Brand> brandList) {
		this.brandList = brandList;
	}

	public ArrayList<Product> getProductList() {
		return productList;
	}

	public void setProductList(ArrayList<Product> productList) {
		this.productList = productList;
	}

	
}
原文链接:https://www.f2er.com/xml/299191.html

猜你在找的XML相关文章