码迷,mamicode.com
首页 > 其他好文 > 详细

解析xml文件

时间:2014-07-01 22:49:34      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:java   文件   os   cti   for   line   

package com.pasc.ams.report.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.security.crypto.codec.Base64;

import com.pasc.ams.commons.AmspmsProperties;
import com.pasc.ams.report.dto.TransferInstructionDireDTO;
import com.pasc.pasmp.core.logging.PasmpLogger;

/**
 * word模板解析工具类
 * 陈超
 *
 * %转换百分比 例子 ${price?‘%‘}
 * ‰转换千分比 例子 ${price?‘‰‘}
 * 转换日期 例子 ${date?‘*:yyyy-MM-dd: 年 月 日 时  分‘}
 * #转换货币 例子 ${price?‘#,####.00‘}
 * >转换大写 例子 ${price?‘>‘}
 *
 */
public class WordTemplateTransfer {
    
    private static final String TEMPLET_PATH = AmspmsProperties.ORDER_TEMPLATE_PATH;
    
    private static final String SIGNATURE_PATH = AmspmsProperties.ORDER_SIGNATURE_PATH;
    
    private static final String BLANK_IMG = "BLANK.png";
    
    /**
     * 解析并填充模板信息
     * @throws Exception
     */
    public String createTransferDoc(String templetName, TransferInstructionDireDTO dto) throws Exception{
        try {
            String fileName = TEMPLET_PATH + templetName;
            String fileStr = fileToString(fileName);
            fileStr = filtFileString(fileStr);
            
            Map<String, Object> map = dto.getMap();
            ReportWordTransferInstructionUtil.setSignValue(map, dto.getSignatureList());
            
            String fileStrValue = transfer(fileStr,map);
            return fileStrValue;
        }  catch (Exception e) {
            e.printStackTrace();
            PasmpLogger.error("", this.getClass(), "createDoc", "创建模板报错!", e);
        }  
        return "";
    }
    
    /**
     * 创建解析并填充了值的word文档--用于测试
     * @throws Exception
     */
    public String createTransferDocTest(String templetName, TransferInstructionDireDTO dto) throws Exception{
        try {
            
            File file = new File("D:\\xml");
            File[] fils = file.listFiles();
            String fileName = "";
            if( fils != null && fils.length > 0 ){
                for( int i=0;i<fils.length ; i++ ){
                    String filePath = fils[i].getAbsolutePath();
                    fileName = fils[i].getName();
                    
                    String fileStr = fileToString(filePath);
                    fileStr = filtFileString(fileStr);
                    String fileStrValue = transfer(fileStr,dto.getMap());
                    
                    //写出部分
                    FileOutputStream fos = null;
                    OutputStreamWriter osw = null;
                    
                    fos = new FileOutputStream("D:\\transXml\\"+fileName+".doc");
                    osw = new OutputStreamWriter(fos, "UTF-8");
                    osw.write(fileStrValue);
                    osw.flush();
                    fos.close();
                    osw.close();
                }
            }
            //System.out.println("fils : " +fils.length );
            //String base = "D:\\xml";
           // String fileName = base + "\\BOHAI.xml";
         
        }  catch (Exception e) {
            e.printStackTrace();
            PasmpLogger.error("", this.getClass(), "createDoc", "创建模板报错!", e);
        }  
        return "";
    }
    
    /**
     * 过滤判断标签
     */
    private String filtFileString(String str){
        String fileStr = str.replaceAll("<#.*?>", "");
        fileStr = fileStr.replaceAll("</#.*?>", "");
        return fileStr;
    }
    
    /**
     * 解析字符串
     */
    public String transfer(String orgStr , Map<String,Object> dataMap){
        if( orgStr == null || "".equals( orgStr.trim() ) ){
            return "";
        }
        String result = replaceValue( orgStr , getValueMap(orgStr,dataMap) );
        return result;
    }
    
    /**
     * 获取所有标签及对应值的map
     */
    private Map<String,String> getValueMap(String orgStr , Map<String,Object> dataMap){
        //获取所有的标签值
        List<String> labels = getSpilt(orgStr);
        Map<String,String> result = new HashMap<String,String>();
        if( labels != null && labels.size() > 0 ){
            for( String label : labels ){
                String labelValue = transferSigleLabel( label , dataMap );
                if( labelValue != null && !"".equals(labelValue) ){
                    result.put( label , labelValue) ;
                }else{
                    result.put( label , "") ;
                }
            }
        }
        return result;
    }
    
    /**
     * 替换所有标签中的值
     */
    private String replaceValue( String orgStr , Map<String,String> valueMap ){
        String reulstValue = orgStr;
        if( valueMap != null && valueMap.size() > 0 ){
            Object objs[] = valueMap.keySet().toArray();
            for( int i = 0 ; i<objs.length;i++ ){
                reulstValue = reulstValue.replace(objs[i].toString(), valueMap.get( objs[i].toString() ));
            }
        }
        return reulstValue;
    }
    
    /**
     * 把标签转换成值字符串
     */
    private String transferSigleLabel(String label , Map<String,Object> dateMap){
        if( dateMap == null || dateMap.size() == 0 || label == null || label.trim().equals("")){
            return "";
        }
        String datePamaramsStr = getSpecial( label );
        String orgFieldStr = getOrgField(label);
        
        String result = "";
        if( datePamaramsStr == null || "".equals( datePamaramsStr ) || datePamaramsStr.indexOf( "&" ) >= 0){
            result = transferString(datePamaramsStr,orgFieldStr,dateMap);
        }else{
            result = transferDate(datePamaramsStr,orgFieldStr,dateMap); //转换日期
            if( "".equals(result) )  result = transferPercent(datePamaramsStr,orgFieldStr,dateMap); //转换百分比
            if( "".equals(result) )  result = transferPermillage(datePamaramsStr,orgFieldStr,dateMap); //转换千分比
            if( "".equals(result) )  result = transferCoin(datePamaramsStr,orgFieldStr,dateMap); //转换货币
            if( "".equals(result) )  result = transferCase(datePamaramsStr,orgFieldStr,dateMap); //转换大小写
            if( "".equals(result) )  result = transferPicture(datePamaramsStr,orgFieldStr,dateMap); //转换图片
        }
        return result;
    }
    
    /**
     * 转换成字符串,如果没有带参数,默认就转换成字符串
     */
    private String transferString(String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( orgFieldStr != null && !"".equals( orgFieldStr ) ){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
                //throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            String value = obj.toString();
            if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( "&" ) >= 0){
                DecimalFormat formatFloat = new DecimalFormat(datePamaramsStr);
                value = formatFloat.format(value);
            }
            return value;
        }
        return "";
    }
    
    /**
     *
     * 获取日期值,返回""说明没有匹配成功,返回null说明dto中没有值,那这个字段就不需要再匹配下面的类型了
     */
    private String transferDate( String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf("*") >= 0 ){
            try {
                String[] params = parseDateParament(datePamaramsStr);
                Object obj = dateMap.get( orgFieldStr );
                if( obj == null ){
                    return params[2];
                    //throw new RuntimeException("没有找到字段:" + orgFieldStr);
                }
               
                SimpleDateFormat sdf = new SimpleDateFormat(params[1]);
                Date value = null;
                if( obj instanceof Date) {
                    value = (Date)obj;
                } else if( obj instanceof String ){
                    value = sdf.parse(obj.toString());
                }
                return sdf.format(value);
            } catch (Exception e) {
                //如果参数不能匹配日期转换,说明不是日期格式
                throw new RuntimeException("日期格式转换出错:" + datePamaramsStr);
            }
        }
        return "";
    }
    
    /**
     * 日期参数转换,因为日期参数比较复杂,是有‘*:yyyy-MM-dd: 年 月 日 时 分‘组成,所以需要特别解析,
     *  年 月 日 时 分 此部分表示值为空时,需要显示的值。
     */
    private String[] parseDateParament(String datePamaramsStr){
        if(datePamaramsStr == null || "".equals( datePamaramsStr ) || datePamaramsStr.indexOf("*")<0 || datePamaramsStr.indexOf(":")<0){
            return null;
        }
        return datePamaramsStr.split(":");
    }
    
    /**
     * 转换百分比
     */
    private String transferPercent(String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( "%" ) >= 0){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
               // throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            String value = obj.toString();
            Double d = Double.parseDouble( value );
            d = d * 100;
            return d.toString() + "%";
        }
        return "";
    }
    
    /**
     * 转换千分比‰  
     */
    private String transferPermillage( String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap  ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( "‰" ) >= 0){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
                //throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            String value = obj.toString();
            Double d = Double.parseDouble( value );
            d = d * 1000;
            return d.toString() + "‰";
        }
        return "";
    }
    
    /**
     * 转换货币
     */
    private String transferCoin(String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( "#" ) >= 0){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
                //throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            String value;
            try {
                value = obj.toString();
                DecimalFormat formatFloat = new DecimalFormat(datePamaramsStr);
                value = formatFloat.format(Double.valueOf(value));
            } catch (RuntimeException e) {
                throw new RuntimeException("货币格式转换出错:" + datePamaramsStr);
            }
            return value;
        }
        return "";
    }
    
    /**
     * 转换大写
     */
    private String transferCase(String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( ">" ) >= 0){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
                //throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            Double value;
            String result = "";
            try {
                value = Double.valueOf(obj.toString());
                result = digitUppercase(value);
            }catch (RuntimeException e) {
                throw new RuntimeException("大小写转换出错:" + datePamaramsStr);
            }
            return result;
        }
        return "";
    }
    
    /**
     * 转换图片
     */
    private String transferPicture(String datePamaramsStr, String orgFieldStr , Map<String,Object> dateMap ){
        if( datePamaramsStr != null && !"".equals( datePamaramsStr ) && datePamaramsStr.indexOf( "@" ) >= 0){
            Object obj = dateMap.get( orgFieldStr );
            if( obj == null ){
                return null;
                //throw new RuntimeException("没有找到字段:" + orgFieldStr);
            }
            String result = "";
            try {
                result = getSignValue(orgFieldStr, dateMap);
            }catch (Exception e) {
                throw new RuntimeException("转换图片出错:" + datePamaramsStr);
            }
            return result;
        }
        return "";
    }
    
    /**
     * 获取标签中的原始字段名
     */
    private String getOrgField( String str ){
        if( str == null || "".equals(str.trim()) || str.indexOf("${") < 0 ){
            return "";
        }
        str = str.replaceAll("<.*?>", "");
        String result = "";
        //没有参数的情况
        if( str.indexOf( "?" ) < 0 ){
            result = str.substring( str.indexOf("{")+1,str.lastIndexOf("}") );
        }else{
            result =str.substring( str.indexOf("{")+1,str.lastIndexOf("?") );
        }
        result = result.replace("!", "");
        result = result.trim();
        return result;
    }
    
    
    /**
     * 获取标签中带‘‘的部分
     */
    private String getSpecial(String str){
        if( str == null || "".equals(str.trim()) || str.indexOf("‘") < 0){
            return "";
        }
        str = str.replaceAll("<.*?>", "");
        String temp = str.substring(str.indexOf("‘")+1,str.lastIndexOf("‘"));
        temp = temp.trim();
        return temp;
    }
    
    /**
     * 获取所有标签元素
     */
    private  List<String> getSpilt(String inputString){
        if (inputString == null || inputString.trim().equals("")) {    
            return null;    
         }
        String regex = "\\$\\{.*?\\}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(inputString);
        List<String> list = new ArrayList<String>();
        while (m.find()) {
            list.add( m.group() );
        }
        return list;
    }
    
    /**
     * 获取图片的base64转码
     */
    public static String getSignValue(String key , Map<String,Object> dateMap) throws Exception{
        Object obj = dateMap.get(key);
        String result = "";
        if (obj != null && !"".equals(obj.toString())) {
            result = getImgString(obj.toString() + ".png");
        } else {
            result = getImgString("");
        }
        return result;
    }
    
    /**
     * 图片转换
     */
    public static String getImgString(String imgName) throws IOException {
            if (imgName == null || "".equals(imgName)) {
                    imgName = BLANK_IMG;
            }
            
            InputStream in = new FileInputStream(new File(SIGNATURE_PATH + imgName));
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            
            return new String(Base64.encode(data));
    }
    
    /**
     * 大小写转换
     */
    public static String digitUppercase(double number) {
            if (0d == number) {
                    return "零";
            }
            if (number >= 1000000000000.0d || number <= -1000000000000.0d) {
                    return "超出系统自动转换范围";
            }
            String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
            String unit[] = {"元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
            String fraction[] = {"分", "角"};
            StringBuilder result = new StringBuilder(32);
            
            if (number < 0d) {
                    result.append("负");
                    number = 0d - number;
            }
            
            long yuan = (long) number;
            int fen = (int) ((number - yuan) * 100);
            
            for (int i = 11; i > -1 ; i--) {
                    int quotient = (int) (yuan / ((long) Math.pow(10, i)));
                    result.append(digit[quotient]).append(unit[i]);
                    yuan -= (long) (Math.pow(10, i) * quotient);
            }
            
            if (fen == 0) {
                    result.append("整");
            } else {
                    for (int i = 1; i > -1; i--) {
                            int quotient = fen / (int) Math.pow(10, i);
                            result.append(digit[quotient]).append(fraction[i]);
                            fen -= (long) (Math.pow(10, i) * quotient);
                    }
            }
                        
            return result.toString().replaceAll("零(仟|佰|拾)", "零")
                                                            .replaceAll("(零)+", "零")
                                                            .replaceAll("亿零万", "亿零")
                                                            .replaceAll("(零)+", "零")
                                                            .replaceAll("零(亿|万|元)", "$1")
                                                            .replaceAll("零角", "零")
                                                            .replaceAll("零分", "")
                                                            .replaceAll("(零)+", "零")
                                                            .replaceAll("^(亿|万|元|角|零)+", "")
                                                            .replaceAll("负(亿|万|元|角|零)+", "负");
    }
    
    /**
     * 文件转换成字符串
     */
    public static String fileToString(String fileName) throws Exception{
        File file = new File( fileName );
        if( file != null && file.exists()){
            StringBuffer sb = new StringBuffer();
            if( file.isFile() ){
                FileInputStream fis = new FileInputStream(fileName);
                InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String text = "";
                while((text = br.readLine()) != null){
                    sb.append( text );
                }
                return sb.toString();
            }
        }
        return "";
    }
}

解析xml文件,布布扣,bubuko.com

解析xml文件

标签:java   文件   os   cti   for   line   

原文地址:http://www.cnblogs.com/chchao/p/3816505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!