参考

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. English trip V1 - B 2. May I Help You? 它是多少钱? Teacher:Lamb Key:

    In this lesson you will learn to ask for things in shops  这节课您将学习如何在商店中寻找东西 课上内容(Lesson) 你通常去哪里购物? W ...

  2. 11月26日11月26日,周日在家practice.基本了解了layouts and Rending (guides); gem font-awesome-rails的实例用法;建立路径route, member..do的实际例子

    http://fontawesome.io/examples/ content_tag(:i,"", class:"fa fa-lock fa-spin fa-lg fa ...

  3. sgu 191 Exhibition

    题意:开始只有某一展台(设为A),有2种操作.1.A展台上放B产品(或者B展台放A产品).2.A展台左边1位放B展台,左边2位放A产品.给出最终产品的排列,问能否实现. 考虑最后一个用2操作的展台,因 ...

  4. webpack热更新

    文件地址:https://pan.baidu.com/s/1kUOwFkV 从昨天下午到今天上午搞了大半天终于把热更新搞好了,之前热更新有两个问题,第一个是不能保存表单状态.第二个是更新太慢,这次主要 ...

  5. android AIDL 语言用法

    跨进程通信可以用AIDL语言 这里讲述下如何使用AIDL语言进行跨进程通信 文章参考 <设计模式>一书 demo结构参考 主要的文件类有:IBankAidl.aidl java文件:Aid ...

  6. ubuntu vi配置

    1.先卸载tiny版本vi 输入命令:sudo apt-get remove vim-common 2.然后再输入命令: sudo apt-get   install vim sudo vim /et ...

  7. Being a Good Boy in Spring Festival HDU - 1850

    桌子上有M堆扑克牌:每堆牌的数量分别为Ni(i=1…M):两人轮流进行:每走一步可以任意选择一堆并取走其中的任意张牌:桌子上的扑克全部取光,则游戏结束:最后一次取牌的人为胜者. 现在我们不想研究到底先 ...

  8. 『MXNet』第三弹_Gluon模型参数

    MXNet中含有init包,它包含了多种模型初始化方法. from mxnet import init, nd from mxnet.gluon import nn net = nn.Sequenti ...

  9. php网站多语言

    1.获取语言的函数: $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); //只取前4位,这样只判断最优先的语言.如果取前5位,可能出现en ...

  10. hdu-6438-贪心

    Buy and Resell Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)To ...