JAXB学习
来源:互联网 发布:白矮星 表面 知乎 编辑:程序博客网 时间:2024/05/16 18:36
JAXB(Java Api for XML Binding).是一项可以根据XML Schema产生Java类的技术。通过该技术,可以轻松的实现XML和JAVA对象的互转。
首先定义个People类,这里需要通过java的Annotation来实现
package com.test.jaxb;import java.util.Date;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="people")public class People {private String name = "";private int age = 0;private Date birthday = null;@XmlAttribute(name="name")public String getName() {return name;}public void setName(String name) {this.name = name;}@XmlElement(name="age")public int getAge() {return age;}public void setAge(int age) {this.age = age;}@XmlElement(name="birthday")public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}
在来个实现方式:
package com.test.jaxb;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;public class JAXBTest {public static void main(String[] args) {JAXBTest jt = new JAXBTest();// 构造对象People people = new People();people.setName("popo");people.setAge(88);try {people.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1949-10-01"));} catch (ParseException e) {e.printStackTrace();}// 对象转换成为XMLjt.beanToXml(people);// 读取XML转换成对象People p = jt.XMLToBean("d://people.xml", People.class);// 输出对象System.out.println(p.getName());System.out.println(p.getAge());System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(p.getBirthday()));}public <T> void beanToXml(T dto){try {JAXBContext context = JAXBContext.newInstance(dto.getClass());Marshaller marshaller = context.createMarshaller();FileOutputStream fos = new FileOutputStream(new File("d://people.xml"));marshaller.marshal(dto, fos);fos.close();} catch (JAXBException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}@SuppressWarnings("unchecked")public <T> T XMLToBean(String xmlPath, Class<T> c){T t = null;try {JAXBContext context = JAXBContext.newInstance(c);Unmarshaller unmarshaller = context.createUnmarshaller();t = (T) unmarshaller.unmarshal(new File(xmlPath));} catch (JAXBException e) {e.printStackTrace();}return t;}}
- jaxb学习
- JAXB学习
- Jaxb 学习
- javaee5 jaxb 学习
- jAXB学习入门
- java JAXB 学习
- JAXB学习笔记
- java JAXB 学习
- JAXB初步的学习
- JAXB学习之注解
- JAXB学习一 (入门)
- JAXB学习三 (验证)
- JAXB
- jaxb
- JAXB
- JAXB
- jaxb
- JAXB
- 绕开QQ通讯录和360的广播中断
- java程序员评定标准
- 33个IOS 手机应用软件界面设计灵感
- android系统开发 AP 和 BP 简要说明
- INNO SETUP 文件关联操作及注册OCX
- JAXB学习
- win7安装iis以及将网站发布到iis上
- C++构造函数用法
- 电脑蓝屏问题追踪的方法
- Servlet 规范笔记—基于http协议的servlet
- android:padding与android:layout_margin;gravity与layout_gravity
- struts2学习小问题解决
- Inno Setup 编程技术全图文教程(转载)
- Speex 语音编解码算法概述