java dom方法生成xml,少量数据时,可以使用

 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class WriteXml{	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void generateXML() throws ParserConfigurationException, IOException, TransformerException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.newDocument();
		//根结点
		Element root = document.createElement("Message"); 
		root.setAttribute("MsgID", "SWPM001");
		root.setAttribute("ResourceID", "SW");
		document.appendChild(root);
		//取得数据
		List<Map> data = this.queryStockInventory();
		for (int i=0;i<data.size();i++) {
			Map<String, String> rec = data.get(i);
			//行结点
			Element dataRow = document.createElement("DataRow"); 
			dataRow.setAttribute("id", String.valueOf(i));
			root.appendChild(document.createTextNode("\n	"));//缩进
			root.appendChild(dataRow);		
			//数据结点
			Iterator it = rec.entrySet().iterator();
			while(it.hasNext()){
				Map.Entry<String, String> entry = (Map.Entry<String, String>)it.next();
				//用字段名作为标签名,对应的数据作为内容 
				Element field = document.createElement(entry.getKey());
				field.appendChild(document.createTextNode(entry.getValue()));
				dataRow.appendChild(document.createTextNode("\n		"));//缩进
				dataRow.appendChild(field);
			}
			dataRow.appendChild(document.createTextNode("\n	"));//缩进
		}
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		//文件名 
		StringBuffer fileName = new StringBuffer("d:\\SWPM001_");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		fileName.append(sdf.format(new Date())).append(".xml");		
		PrintWriter pw = new PrintWriter(new FileOutputStream(fileName.toString()));
		StreamResult result = new StreamResult(pw);
		DOMSource source = new DOMSource(document);
		transformer.transform(source, result);
	}
	
	
	@SuppressWarnings("rawtypes")
	private List queryStockInventory() {
		StringBuffer insertInto = new StringBuffer();	
		insertInto.append("SELECT *")				
				.append(" FROM table")
				.append(" WHERE  rownum<=10"); //库存数量
		return _dao.query(insertInto.toString());
	}
}

你可能感兴趣的:(java,DAO,xml)