Java tutorial
/** * PureInfo Dolphin * @(#)XmlExporterImpl.java 1.0 Sep 29, 2005 * * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. * All rights reserved, see the license file. * * www.pureinfo.com.cn */ package com.pureinfo.dolphin.export.impl; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.pureinfo.dolphin.export.IExporter; import com.pureinfo.dolphin.export.model.DolphinExportGoods; import com.pureinfo.dolphin.export.model.IExportGoods; import com.pureinfo.force.ForceConstants; import com.pureinfo.force.exception.PureException; import com.pureinfo.force.exception.PureRuntimeException; /** * <P> * Created on Sep 29, 2005 3:38:55 PM <BR> * Last modified on Sep 29, 2005 * </P> * * @author Freeman.Hu * @version 1.0, Sep 29, 2005 * @since Dolphin 1.0 */ public class XmlExporterImpl implements IExporter { /** * @see com.pureinfo.dolphin.export.IExporter#export(OutputStream, * DolphinExportGoods) */ public void export(OutputStream _os, IExportGoods _goods) throws PureException { try { //1. to create XML element Document doc = DocumentHelper.createDocument(); Element root = doc.addElement(_goods.getName()); //2. to prepare column names if (!_goods.hasHeader()) { throw new PureRuntimeException(PureException.SETTING_MISSING, "headers required in goods"); } String[] colNames = _goods.getHeaders(); //3. to export data Object[] values; Iterator iter = _goods.iterator(); while (iter.hasNext()) { values = _goods.unpackGoods(iter.next()); exportRow(root, values, colNames); } //4. to output to stream new XMLWriter(_os, OutputFormat.createPrettyPrint()).write(doc); } catch (Exception ex) { throw new PureException(PureException.UNKNOWN, "", ex); } } /** * Exports one row to XML * * @param _parent * parent element * @param _colValues * column values * @param _colNames * column names * @throws Exception * if failed. */ public static void exportRow(Element _parent, Object[] _colValues, String[] _colNames) throws Exception { Object value; String sValue; Element rowEle, colEle; rowEle = _parent.addElement("row"); for (int i = 0; i < _colValues.length; i++) { colEle = rowEle.addElement(_colNames[i]); value = _colValues[i]; if (value == null) continue; //else if (value instanceof Date) { sValue = ForceConstants.DATE_FORMAT.format((Date) value); } else if (value instanceof Calendar) { sValue = ForceConstants.DATE_FORMAT.format(((Calendar) value).getTime()); } else { sValue = value.toString(); } colEle.addText(sValue); } } }