Xml文件转化为对象,对象转化为Xml

前端之家收集整理的这篇文章主要介绍了Xml文件转化为对象,对象转化为Xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Stream用来将xml转化为对象,或则将对象转化为xml,xml与Json的转化也可以借助它

首先下载jar包:

xstream-XXX.jar xpp3-XXX.jar

可以点击这里下载http://download.csdn.net/detail/mejustdoit/8901831

关于转换最主要的就是两个

新建Stream对象


  
 XStreamxstream = new XStream();或 
 XStreamxstream = new XStream(new DomDriver()); // 需要xpp3 jar 
 

xstream.alias("标签名",类名);//标签名与类名映射

例如:xstream.alias("Head",head.class);

如果没有映射得到的xml文件标签里包含了包名

 //包重命名 
 
xstream.aliasPackage("现在包名","以前包名");
 
 

OBJ obj = (OBJ)xstream.fromXML(xml);//得到的obj就是对象

String xml = xstream.toXML(obj);//得到的xml就是xml文件

简单介绍之后下面是代码目录结构

//用来选择xml文件保存位置,或者选择xml文件
public class FileChoice {
	private static JFileChooser fileChooser = null;
	private static JFileChooser fileDown = null;
	private static String importPath = "";
	private static String exportPath = "";
	// 选择框

		private static JFileChooser getFileChooser() {
			if (fileChooser == null) {
				fileChooser = new JFileChooser();
				fileChooser.setFileFilter(null);
				fileChooser.setFileFilter(new FileNameExtensionFilter(
						"XML Files","xml"));
				fileChooser.setFont(new Font("Dialog",Font.PLAIN,12));
				fileChooser.setMultiSelectionEnabled(false);
			}
			return fileChooser;
		}

		public  String getUploadFile() {
			
			int res = getFileChooser().showDialog(new JLabel(),"选择文件");
			if (res == JFileChooser.APPROVE_OPTION) {
				File file = getFileChooser().getSelectedFile();
				importPath = file.getAbsolutePath();
				System.out.println("ccccccccccccccccc:" + file.getAbsolutePath());
			}
			return importPath;
		}

		// 保存框
		public static String getFileDown() {
			if (fileDown == null) {
				fileDown = new JFileChooser();
				fileDown.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			}
			int returnVal = fileDown.showDialog(new JLabel(),"选择保存位置");
			//int returnVal = fileDown.showOpenDialog(null);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				System.out.println("You chose diriction: "
						+ fileDown.getSelectedFile().getPath());
				exportPath = fileDown.getSelectedFile().getPath() + "\\";
				System.out.println(exportPath + "ddddddddd");
			}
			return exportPath;
		} 
}

文件的前三个字节判断编码值,在确定解码方式

编码理解:http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/

package com.gpl.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
//判断文件是什么类型,因为文件前三个字节基本上都会给出文件编码类型所以就选择前三个字节判断
//如果对于没给出的自己就选择自己传参数带入,在InputXmlObj类里有体现
public class JudgeCharset {
	public String getCharset( File file) { 
        String charset = "GBK";  
        byte[] first3Bytes = new byte[3];  
        try {  
            boolean checked = false;  
            BufferedInputStream bis = new BufferedInputStream(  
                    new FileInputStream(file));  
            bis.mark(0);  
            int read = bis.read(first3Bytes,3);  
            if (read == -1)  
                return charset;  
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {  
                charset = "UTF-16LE";  
                checked = true;  
            } else if (first3Bytes[0] == (byte) 0xFE  
                    && first3Bytes[1] == (byte) 0xFF) {  
                charset = "UTF-16BE";  
                checked = true;  
            } else if (first3Bytes[0] == (byte) 0xEF  
                    && first3Bytes[1] == (byte) 0xBB  
                    && first3Bytes[2] == (byte) 0xBF) {  
                charset = "UTF-8";  
                checked = true;  
            }  
            bis.reset();  
            if (!checked) {  
                int loc = 0;  
                while ((read = bis.read()) != -1) {  
                    loc++;  
                    if (read >= 0xF0)  
                        break;  
                    if (0x80 <= read && read <= 0xBF)  
                        break;  
                    if (0xC0 <= read && read <= 0xDF) {  
                        read = bis.read();  
                        if (0x80 <= read && read <= 0xBF)  
                            continue;  
                        else  
                            break;  
                    } else if (0xE0 <= read && read <= 0xEF) {  
                        read = bis.read();  
                        if (0x80 <= read && read <= 0xBF) {  
                            read = bis.read();  
                            if (0x80 <= read && read <= 0xBF) {  
                                charset = "UTF-8";  
                                break;  
                            } else  
                                break;  
                        } else  
                            break;  
                    }  
                }  
            }  
            bis.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        System.out.println("charset:  "+charset);
        return charset;  
    }  
}

java类如下
public class head {
	private String 	MessageType;//报文类型
	private String  MessageID;//报文编号
	private String  ENT_NO;//平台企业备案号  企业在海关备案申报系统中的备案号;
	private String MessageDate;//报文日期
	public String getMessageType() {
		return MessageType;
	}
	public void setMessageType(String messageType) {
		MessageType = messageType;
	}
	public String getMessageID() {
		return MessageID;
	}
	public void setMessageID(String messageID) {
		MessageID = messageID;
	}
	public String getENT_NO() {
		return ENT_NO;
	}
	public void setENT_NO(String eNT_NO) {
		ENT_NO = eNT_NO;
	}
	public String getMessageDate() {
		return MessageDate;
	}
	public void setMessageDate(String messageDate) {
		MessageDate = messageDate;
	}
	@Override
	public String toString() {
		return "Head [MessageType=" + MessageType + ",MessageID=" + MessageID
				+ ",ENT_NO=" + ENT_NO + ",MessageDate=" + MessageDate + "]";
	}
	
}
下面简写
public class taxList {

	private String G_NO;// 序号
	private String LIST_NO;// 进境清单编号
	private String ENT_INSIDE_NO;// 进境清单编号
	private String COP_G_NO;// 商品货号*
	private String G_NAME;// 商品名称
	private String G_MODEL;// 规格型号*
	private String UNIT;// 申报计量单位*
	private int QTY;// 申报数量
	private double DEC_TOTAL;// 申报总价*DECIMAL(19,5)
	private double POST_TAX;// 行邮税率*DECIMAL(19,5)
	private double POST_TOTAL;// 行邮税额*DECIMAL(19,5)
	private String CHK_DATE;// 审核日期
	private String CUSTOMS_CODE;// 关区代码
	private String REGION_CODE;// 监管场所码
	private String POST_TARIFF_CODE;// 监管场所码行邮税号
}

public class declaration {
private taxHead TaxHead;

private List<taxList> TaxLists;

public taxHead getTaxHead() {
	return TaxHead;
}
public void setTaxHead(taxHead taxHead) {
	TaxHead = taxHead;
}
public List<taxList> getTaxLists() {
	return TaxLists;
}
public void setTaxLists(List<taxList> taxLists) {
	TaxLists = taxLists;
}
@Override
public String toString() {
	return "declaration [TaxHead=" + TaxHead + ",TaxLists=" + TaxLists + "]";
}

}


public class taxHead {

private String TAXABLE_NO;//计税处理编号
private String TAX_NUMBER ;//个人税单号
private String RECEIVE_NAME;//订单人姓名
private String RECEIVE_NUM;//订单人证件号
private  double TAX_TOTAL;//计税物品总值DECIMAL(19,5)
private  double POST_SUM ;//DECIMAL(19,5)行邮税税额
private  double RATEABLE_TOTAL;//应征税额DECIMAL(19,5)
private String RECEIVE_ADDR;//收件人地址
private String I_E_FALG;//进出口标志:E-出口;I-进口;
private String ENT_NO;//平台企业备案号    收件人姓名对应的平台企业;进境电子清单的平台企业备案号;
private String TRADE_CODE;//平台企业代码
private String TRADE_NAME;//平台企业名称
private String ORG_CODE;//组织机构代码
private String CUSTOMS_CODE;//关区代码
private String TAXABLE_DATE;//计税日期
private String LIST_G_DATE;//清单放行日期
private int GOOD_SUM;//商品项数
private String TAX_NOTE ;//征税备注


}

public class message {
private head Head;
private declaration Declaration;
public head getHead() {
	return Head;
}
public void setHead(head head) {
	Head = head;
}
public declaration getDeclaration() {
	return Declaration;
}
public void setDeclaration(declaration declaration) {
	Declaration = declaration;
}
@Override
public String toString() {
	return "message [Head=" + Head + ",Declaration=" + Declaration + "]";
}




}

public class InputXml2Obj {
	private static String filein = " ";
	private static String fileout = "";
	private static String xml;
	private static String str;
	private static String encoding = "utf-8";
	private static message Message = null;
	private static FileChoice filechoice = null;
	private JudgeCharset judgeCharset;

	public static FileChoice getFilechoice() {
		if (filechoice == null)
			filechoice = new FileChoice();
		return filechoice;
	}

	public static void setFilechoice(FileChoice filechoice) {
		InputXml2Obj.filechoice = filechoice;
	}
	
	public JudgeCharset getJudgeCharset() {
		if(judgeCharset == null){
			judgeCharset = new JudgeCharset();
		}
		return judgeCharset;
	}
	public static void main(String[] args) {
		
		InputXml2Obj inputXml2Obj = new InputXml2Obj();
		/*System.out.println("OBJ:  "+inputXml2Obj.readMessageFromXml());
		inputXml2Obj.readMessageToXml(inputXml2Obj.readMessageFromXml());*/
		inputXml2Obj.readMessageFromXml("utf-8");

	}
	//从xml文件中读取内容生成obj
	public   message readMessageFromXml() {
		filechoice = getFilechoice();
		filein = filechoice.getUploadFile();
		File file = new File(filein);
		 encoding = getJudgeCharset().getCharset(file);
		XStream xstream = new XStream();
		xstream.alias("Head",head.class);
		xstream.alias("TaxHead",taxHead.class);
		xstream.alias("TaxList",taxList.class);
		xstream.alias("Declaration",declaration.class);
		xstream.alias("Message",message.class);
		// File file = new File(filein);
		/*
		 * try { InputStreamReader o = new FileReader(file); Reader reader = new
		 * InputStreamReader(new FileInputStream(file),"UTF-8"); Message =
		 * (message) xstream.fromXML(o); // str = xstream.toXML(Message); //
		 * System.out.println(str); // message Message1 = (message)
		 * xstream.fromXML(str); System.out.println(Message); } catch (Exception
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); } return
		 * Message; }
		 */
		try {
			 Message = (message) xstream.fromXML(read(filein,encoding));
			System.out.println("Message:"+Message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Message;
	}

	//从xml文件中读取内容生成obj(含参)
	public static  message readMessageFromXml(String charset) {
		filechoice = getFilechoice();
		filein = filechoice.getUploadFile();
		XStream xstream = new XStream();
		xstream.alias("Head",message.class);
		try {
			 Message = (message) xstream.fromXML(read(filein,charset));
			System.out.println("Message:"+Message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Message;
	}
	// 如果不写好判断编码方式会有编码方式错误
	//读取XML文件
	public static String read(String path,String encoding) throws IOException {
		String content = "";
		File file = new File(path);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file),encoding));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			content += line + "\n";
		}
		reader.close();
		return content;
	}

	// 写XML文件
	public static void write(String path,String content,String encoding)
			throws IOException {
		File file = new File(path);
		file.delete();
		file.createNewFile();
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file),encoding));
		writer.write(content);
		writer.close();
	}
//将OBJ转化成xml文件写出(含参)
	public static  void readMessageToXml(message Message,String charset) {	
		filechoice = getFilechoice();
		fileout = filechoice.getFileDown();//获取输出位置
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("Head",message.class);
		str = "<?xml version='1.0' "+"encoding='"+charset+"'?>"+"\n"+xstream.toXML(Message);
		System.out.println("str:  "+str);
		try {
			write(fileout + "\\89.xml",str,charset);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println(str);

	}
	
	
	public static  void readMessageToXml(message Message) {
		filechoice = getFilechoice();
		fileout = filechoice.getFileDown();//获取输出位置
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("Head",message.class);
		str = "<?xml version='1.0' "+"encoding='"+encoding+"'?>"+"\n"+xstream.toXML(Message);
		System.out.println("str:  "+str);
		try {
			write(fileout + "\\89.xml",encoding);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println(str);

	}
	//判断编码内容
	
}

生成的结果:
<?xml version="1.0" encoding="utf-8"?>
<Message>
  <Head>
    <MessageType>881110</MessageType>
    <MessageID>8811102015070657e35b5dd2bc4048a118810d8a1d6be6</MessageID>
    <ENT_NO>PTE51651404290000001</ENT_NO>
    <MessageDate>2015-07-06 01:13:07</MessageDate>
  </Head>
  <Declaration>
    <TaxHead>
      <TAXABLE_NO>XYS5165507060002513</TAXABLE_NO>
      <TAX_NUMBER />
      <RECEIVE_NAME>云昊然</RECEIVE_NAME>
      <RECEIVE_NUM>440102197805271193</RECEIVE_NUM>
      <TAX_TOTAL>484</TAX_TOTAL>
      <POST_SUM>48.40</POST_SUM>
      <RATEABLE_TOTAL>0</RATEABLE_TOTAL>
      <RECEIVE_ADDR>广东省 深圳市 罗湖区 罗湖大厦6栋13楼C</RECEIVE_ADDR>
      <I_E_FALG>I</I_E_FALG>
      <ENT_NO>PTE51651404290000001</ENT_NO>
      <TRADE_CODE>4430665006</TRADE_CODE>
      <TRADE_NAME>广州市天宁货运代理有限公司(南沙)</TRADE_NAME>
      <ORG_CODE>563998783</ORG_CODE>
      <CUSTOMS_CODE>5165</CUSTOMS_CODE>
      <TAXABLE_DATE>2015/7/6 1:13:04</TAXABLE_DATE>
      <LIST_G_DATE>2015/7/5 15:40:05</LIST_G_DATE>
      <GOOD_SUM>1</GOOD_SUM>
      <TAX_NOTE />
    </TaxHead>
    <TaxLists>
      <TaxList>
        <G_NO>1</G_NO>
        <LIST_NO>JKE5165F507050002784</LIST_NO>
        <ENT_INSIDE_NO />
        <COP_G_NO>138</COP_G_NO>
        <G_NAME>荷兰Nutrilon牛栏奶粉 5段</G_NAME>
        <G_MODEL>2岁以上 800g</G_MODEL>
        <UNIT>122</UNIT>
        <QTY>4</QTY>
        <DEC_TOTAL>484</DEC_TOTAL>
        <POST_TAX>0.10</POST_TAX>
        <POST_TOTAL>48.40</POST_TOTAL>
        <CHK_DATE>2015/7/5 15:40:05</CHK_DATE>
        <CUSTOMS_CODE>5165</CUSTOMS_CODE>
        <REGION_CODE>51651</REGION_CODE>
        <POST_TARIFF_CODE />
      </TaxList>
    </TaxLists>
  </Declaration>
</Message>
参考:

http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

http://my.oschina.net/exit/blog/156613

http://liuzidong.iteye.com/blog/1059453

工程下载

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

猜你在找的XML相关文章