参考

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. Asp.net博客系统收集和简单介绍

    国内Asp.net博客系统收集和简单介绍       [转载文章,仅供个人参考,引自http://www.soyaoo.com/Blog/post/92.html] 1.ZJ-Blog程序简介:基于A ...

  2. LeetCode--371--两整数之和

    问题描述: 方法: class Solution(object): def getSum(self, a, b): """ :type a: int :type b: i ...

  3. bzoj3675

    题解:首先要明确一件事,就是当分割的方案固定时,无论先分割的哪一段,结果都是不变的,然后能列出dp方程:\(dp[i][j]=max(dp[k][j-1]+(a[i]-a[k])*(a[n]-a[i] ...

  4. python-flask-SQLAlchemy-Utils组件

    SQLAlchemy-Utils,提供choice功能 定义: # pip3 install sqlalchemy-utils from sqlalchemy_utils import ChoiceT ...

  5. zend framwork黑箱测试

    1.我采用的测试时phpunit 1).按照:https://phpunit.de/  把下载的文件放到C:/window 目录,让后修改一下文件的后缀,使在敲击命令的时候可以不用敲文件的全称 如:p ...

  6. Java异常及错误

    java提供了两种异常机制,可以分为运行时异常(RuntimeException)与检查式异常(checked Exception). 检查式异常:java编译器对于这种异常需要我们对其用try... ...

  7. 安卓——Handler延迟跳转

    //声明控制对象 Handler handler =new Handler(){ @Override public void handleMessage(Message msg) { super.ha ...

  8. 判断input[type=file]上传文件格式

    input type="file" 在js中判断文件上传类型 function onSubmit(){ var form1 = document.forms[0]; var fil ...

  9. LINQ 中常用函数使用: Take TakeWhile Skip SkipWhile Reverse Distinct

    1,Take 方法 Take方法用于从一个序列的开头返回指定数量的元素. string[] names = { "郭靖", "李莫愁", "欧阳晓晓& ...

  10. 数据结构与算法之PHP查找算法(二分查找)

    二分查找又称折半查找,只对有序的数组有效. 优点是比较次数少,查找速度快,平均性能好,占用系统内存较少: 缺点是要求待查表为有序表,且插入删除困难. 因此,折半查找方法适用于不经常变动而查找频繁的有序 ...