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

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

首先下载jar包:

xstream-XXX.jar xpp3-XXX.jar

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

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

新建Stream对象


XStream xstream = new XStream();或 XStream xstream
= 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, 0, 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", head.class);
		xstream.alias("TaxHead", taxHead.class);
		xstream.alias("TaxList", taxList.class);
		xstream.alias("Declaration", declaration.class);
		xstream.alias("Message", 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", head.class);
		xstream.alias("TaxHead", taxHead.class);
		xstream.alias("TaxList", taxList.class);
		xstream.alias("Declaration", declaration.class);
		xstream.alias("Message", 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", head.class);
		xstream.alias("TaxHead", taxHead.class);
		xstream.alias("TaxList", taxList.class);
		xstream.alias("Declaration", declaration.class);
		xstream.alias("Message", message.class);
		str = "<?xml version='1.0' "+"encoding='"+encoding+"'?>"+"\n"+xstream.toXML(Message);
		System.out.println("str:  "+str);
		try {
			write(fileout + "\\89.xml", str, 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

工程下载

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-11-05 22:07:55

Xml文件转化为对象,对象转化为Xml的相关文章

java 使用xom对象数据序列化为xml、反序列化、Preferences相关操作小案例

package org.rui.io.xml; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; import nu.xom.Document; import nu.

C#针对xml文件转化Dictionary的方法

本文实例讲述了C#针对xml文件转化Dictionary的方法.分享给大家供大家参考.具体实现方法如下: 下面是xml文件: 代码如下: <?xml version="1.0″ encoding="utf-8″ ?> <nodes> <国土局> <name>市局国土资源局</name> <code>330</code> <受理 telephone="88205156″>萍,倩<

自定义类库:Java转换xml文件转化pojo工具

一.之前java读取xml配置文件时,总是通过dom4j第三方库主动解析,最近发现可以通过jdk类库将xml转换pojo. 二.编写xml转化工具类XmlUtils package com.moy.demo.common.utils; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java.io.InputStream; import java.io.Reader; import jav

转: JaxbContext生成xml文件或java类对象转化注解

JAXB(Java API for XML Binding),提供了一个快速便捷的方式将Java对象与XML进行转换.在JAX-WS(Java的WebService规范之一)中,JDK1.6 自带的版本JAX-WS2.1,其底层支持就是JAXB. JAXB 可以实现Java对象与XML的相互转换,在JAXB中,将一个Java对象转换为XML的过程称之为Marshal,将XML转换为Java对象的过程称之为UnMarshal.我们可以通过在Java 类中标注注解的方式将一个Java对象绑定到一段X

解析服务器端回传 XML 文件并封装为对象

起因 项目的上游数据对接方通过XML文件与主体项目进行通信,获取其XML的方法为通过HTTP的GET请求返回XML文件,之前还未遇到过这种传递方式,就稍微查了一下资料,写了一个出来,如果你也有类似的需求,可供参考. 正文 整个"接收-存储-查询-赋值"由两个模块组成,即"接收-存储"与"查询-赋值",配合一个用于封装的实体类与一个提高复用性的"Date-String"转换工具类. 整体的思路很简单,首先用java的"

sax解析xml文件,封装到对象中

创建User.java类 public class User { private String id; private String name; private String age; private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public

Android程序解析XML文件的方法及使用PULL解析XML案例

一.一般解析XML文件的方法有SAX和DOM.PULL (1)DOM(JAXP Crimson解析器) DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找特定信息.分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作.由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的.DOM 以及广义的基于树的处理具有几个优点.首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构

.net中xml文件的导入使用(包括创建xml和导入xml)

上次有说到.net 创建xml文件的方法(一种固定方式,一种动态方法),这次记录一下怎样导入xml文件 1.导入xml文件的方法 1)xml文件格式 2) 窗体页面的样式 3)源码实例 3.1)创建xml文件的源码 /// <summary> /// 灵活方式模板 /// </summary> /// <param name="sender"></param> /// <param name="e"><

将XML文件转化成NSData对象

NSData *xmlData = [[NSData alloc]initWithContentsOfFile:[NSString stringWithFormat:@"%@/People.xml",[[NSBundle mainBundle] resourcePath]]]; //2.将xmlData转化成xml文档 GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData option