参考

http://blog.csdn.net/yanan_seachange/article/details/7325708

a.添加依赖

b.建立绑定关系

c.测试

a.添加依赖

<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.2.</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.</version>
</dependency>
</dependency>

b.建立绑定关系

package com.yun.jaxb;

import java.util.Vector;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="earth")
public class Earth {
private String description="earth";
private Vector<Country> countries;
@XmlAttribute
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@XmlElementWrapper(name="countrys")
@XmlElement(name="country")
public Vector<Country> getCountries() {
return countries;
}
public void setCountries(Vector<Country> countries) {
this.countries = countries;
}
}
package com.yun.jaxb;

import java.util.Vector;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="country")
public class Country {
private String description;
private String name;
private Vector<Province> provinces;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@XmlElementWrapper(name="provinces")
@XmlElement(name="province")//如果provice对象中没有集合或者数组类型的属性了,该注解可以省略。否则,它是必须的。
public Vector<Province> getProvinces() {
return provinces;
}
public void setProvinces(Vector<Province> provinces) {
this.provinces = provinces;
}
}
package com.yun.jaxb;

import java.util.Vector;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="province")
public class Province {
private String name;
private Vector<City> cities;
@XmlElementWrapper(name="cities")
@XmlElement(name="city")
public Vector<City> getCities() {
return cities;
}
public void setCities(Vector<City> cities) {
this.cities = cities;
}
@XmlElement()
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.yun.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="city")
public class City {
private String name;
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

c.测试

public static void vectorXml() {
City zhengzhou=new City();
City jinan=new City();
zhengzhou.setName("郑州");
jinan.setName("济南"); Province henan=new Province();
henan.setName("河南");
Vector<City> henanCity=new Vector<City>();
henanCity.add(zhengzhou);
henan.setCities(henanCity);
Province shandong=new Province();
shandong.setName("山东");
Vector<City> sdCity=new Vector<City>();
sdCity.add(zhengzhou);
henan.setCities(sdCity); Country country=new Country();
country.setDescription("这里是天朝");
country.setName("中国");
Vector<Province> provinces=new Vector<Province>();
provinces.add(henan);
provinces.add(shandong);
country.setProvinces(provinces); Earth earth=new Earth();
earth.setDescription("地球...");
Vector<Country> countrys=new Vector<Country>();
countrys.add(country);
earth.setCountries(countrys); FileOutputStream outPut=null;
try {
outPut=new FileOutputStream("earth.xml");
JAXBContext jc=JAXBContext.newInstance(Earth.class);
Marshaller m=jc.createMarshaller();
m.marshal(earth, outPut);
} catch(Exception e){
e.printStackTrace();
}
finally {
try {
outPut.close();
} catch (IOException e) { }
}
}

结果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<earth description="地球...">
<countrys>
<country>
<description>这里是天朝</description>
<name>中国</name>
<provinces>
<province>
<cities>
<city>
<name>郑州</name>
</city>
</cities>
<name>河南</name>
</province>
<province>
<name>山东</name>
</province>
</provinces>
</country>
</countrys>
</earth>

解析:

 public static void unmarshalVectorXml() {
try {
File file = new File("earth.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Earth.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Earth earth = (Earth) jaxbUnmarshaller.unmarshal(file);
System.out.println(earth);
} catch (JAXBException e) {
e.printStackTrace();
}
}

封装util

package com.yun.xml.util;

import java.io.ByteArrayOutputStream;
import java.io.StringReader; import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter; public class JaxbUtil { private static final String ENCODING_UTF8 = "UTF8"; /**
* JavaBean转换成xml
*
* @param obj
* @param encoding
* @return
*/
public static String convertToXml(Object obj) { try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, JaxbUtil.ENCODING_UTF8);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); ByteArrayOutputStream baos = new ByteArrayOutputStream();
//注意jdk版本
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = xmlOutputFactory
.createXMLStreamWriter(baos, (String) marshaller
.getProperty(Marshaller.JAXB_ENCODING));
xmlStreamWriter.writeStartDocument(
(String) marshaller.getProperty(Marshaller.JAXB_ENCODING),
"1.0");
marshaller.marshal(obj, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
return new String(baos.toString(JaxbUtil.ENCODING_UTF8)); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; } /**
* xml转换成JavaBean
*
* @param xml
* @param c
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T converyToJavaBean(String xml, Class<T> c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
} return t;
} }

 测试

package com.yun.xml.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller; import com.yun.xml.bo.City;
import com.yun.xml.bo.Country;
import com.yun.xml.bo.Earth;
import com.yun.xml.bo.Province;
import com.yun.xml.util.JaxbUtil; public class XmlTest { public static void unmarshalVectorXml() {
try {
File file = new File("earth.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Earth.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Earth earth = (Earth) jaxbUnmarshaller.unmarshal(file);
System.out.println(earth);
} catch (JAXBException e) {
e.printStackTrace();
}
} public static void marshalVectorXml() {
Earth earth = installBean();
FileOutputStream outPut=null;
try {
outPut=new FileOutputStream("earth.xml");
JAXBContext jc=JAXBContext.newInstance(Earth.class);
Marshaller m=jc.createMarshaller();
m.marshal(earth, outPut);
} catch(Exception e){
e.printStackTrace();
}
finally {
try {
outPut.close();
} catch (IOException e) { }
}
} private static Earth installBean() {
City zhengzhou=new City();
City jinan=new City();
zhengzhou.setName("郑州");
jinan.setName("济南"); Province henan=new Province();
henan.setName("河南");
Vector<City> henanCity=new Vector<City>();
henanCity.add(zhengzhou);
henan.setCities(henanCity);
Province shandong=new Province();
shandong.setName("山东");
Vector<City> sdCity=new Vector<City>();
sdCity.add(zhengzhou);
henan.setCities(sdCity); Country country=new Country();
country.setDescription("这里是天朝");
country.setName("中国");
Vector<Province> provinces=new Vector<Province>();
provinces.add(henan);
provinces.add(shandong);
country.setProvinces(provinces); Earth earth=new Earth();
earth.setDescription("地球...");
Vector<Country> countrys=new Vector<Country>();
countrys.add(country);
earth.setCountries(countrys);
return earth;
} public static String toXml() {
Earth earth = installBean();
return JaxbUtil.convertToXml(earth);
} public static Earth toBean() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF8\"?><earth description=\"地球...\"><countrys><country><description>这里是天朝</description><name>中国</name><provinces><province><cities><city><name>郑州</name></city></cities><name>河南</name></province><province><name>山东</name></province></provinces></country></countrys></earth>";
return JaxbUtil.converyToJavaBean(xml, Earth.class);
} public static void main(String[] args) {
// marshalVectorXml();
// unmarshalVectorXml();
System.out.println(toXml());
Earth earth = toBean();
System.out.println(earth.getDescription());
} }

  

jaxb 组装及解析xml的更多相关文章

  1. java生成解析xml的另外两种方法Xstream

    Xstream生成和解析xm和JAXB生成和解析xml的方法. 一,Xstream Xstream非jdk自带的,需要到入Xstream-1.4.3.jar和xpp3_min-1.1.4.jar 1. ...

  2. 使用JAXB解析xml文件(一)

      1.java中解析xml的几种方式 1.1 JDK原生dom形式 原理:一次性把xml读入内存,在内存中构建成树形结构.优点:对节点操作方便,缺点:需要大量的内存空间,浪费资源 1.2 SAX形式 ...

  3. JAXB解析XML为对象

    JAXB支持注解将XML转化为对象,具体看一个简单的例子: <?xml version="1.0" encoding="utf-8"?> <A ...

  4. dom4j组装xml 以及解析xml

    dom4j组装xml 以及解析xml: 1.下载dom4j的jar包,地址:https://dom4j.github.io/ 2.java代码: package test; import java.i ...

  5. jaxb解析xml工具类

    [quote]jaxb jdk 自带的解析xml的一种方式支持,只需要用注解对javabean进行数据绑定[/quote] package com.nnk.flowrecharge.common;im ...

  6. webservice04#对象与xml转换-jaxb#Stax解析xml#新建修改xml

    1,Student类 package com.yangw.xml; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement / ...

  7. 解析xml并且导入mysql

    https://www.zhihu.com/question/28139319 解析超过500G的xml 写入mysql,如何尽快写入? 解析超过500G的xml 写入mysql,如何尽快写入? 现在 ...

  8. java 中解析xml的技术

    最初,XML 语言仅仅是意图用来作为 HTML 语言的替代品而出现的,但是随着该语言的不断发展和完善,人们越来越发现它所具有的优点:例如标记语言可扩展,严格的语法规定,可使用有意义的标记,内容存储和表 ...

  9. Java Dom解析xml

    Dom解析是将xml文件全部载入,组装成一颗dom树,然后通过节点以及节点之间的关系来解析xml文件,下面结合这个xml文件来进行dom解析. <?xml version="1.0&q ...

随机推荐

  1. PHP策略模式demo

    <?php//策略模式就是你有很多的方法,选择一种适合自己的,// 单例模式就是只有一个实例对象,不需要每个文件都要加载,比如连接数据库,// 工厂模式就是//策略模式interface cha ...

  2. Educational Codeforces Round 2 E - Lomsat gelral

    题意:每个节点有个值,求每个节点子树众数和 题解:可线段树合并,维护每个数出现次数和最大出现次数,以及最大出现次数的数的和 //#pragma GCC optimize(2) //#pragma GC ...

  3. 基于spring的web项目启动时预加载数据到ServletContext

    1.要在web启动时预加载数据到ServletContext,实现方法有很多,一种比较简单的方案就是: 1)新建一个bean,定义其初始化方法: <bean id="beanId&qu ...

  4. spring boot 2.0(二)动态banner的支持

    Spring Boot 2.0 提供了很多新特性,其中就有一个小彩蛋:动态 Banner,今天我们就先拿这个来尝尝鲜. 配置依赖 使用 Spring Boot 2.0 首先需要将项目依赖包替换为刚刚发 ...

  5. oracle的 表、 procedure、package等对象被锁,处理方法

    1.0  oracle中表被锁,处理方法 select t4.object_name, t3.spid, t1.oracle_username, t1.os_user_name  from v$pro ...

  6. Leetcode 1002. 查找常用字符

    1002. 查找常用字符  显示英文描述 我的提交返回竞赛   用户通过次数301 用户尝试次数324 通过次数303 提交次数480 题目难度Easy 给定仅有小写字母组成的字符串数组 A,返回列表 ...

  7. mybatis*中DefaultVFS的logger乱码问题

    从网上下的Java Persistence with MyBatis 3的源码 出现这个问题的原因是logback记日志的时候乱码 ResolverUtil - Not a JAR: file:... ...

  8. 在MongoDB中执行查询、创建索引

    1. MongoDB中数据查询的方法 (1)find函数的使用: (2)条件操作符: (3)distinct找出给定键所有不同的值: (4)group分组: (5)游标: (6)存储过程. 文档查找 ...

  9. springboot自动装配

    Spring Boot自动配置原理 springboot自动装配 springboot配置文件 Spring Boot的出现,得益于“习惯优于配置”的理念,没有繁琐的配置.难以集成的内容(大多数流行第 ...

  10. js 获取数组重复的元素

    //获取数组重复的元素 function refrain(arr) { var tmp = []; if(Array.isArray(arr)) { arr.concat().sort().sort( ...