一、jaxb是什么

  JAXB是Java Architecture for XML Binding的缩写。可以将一个Java对象转变成为XML格式,反之亦然。
     我们把对象与关系数据库之间的映射称为ORM,其实也可以把对象与XML之间的映射称为OXM(Object XML Mapping)。原来JAXB是Java EE的一部分,在JDK1.6中,SUN将其放到了Java SE中,这也是SUN的一贯做法。JDK1.6中自带的这个JAXB版本是2.0,比起1.0(JSR 31)来,JAXB2(JSR 222)用JDK5的新特性Annotation来标识要作绑定的类和属性等,这就极大简化了开发的工作量。

二、jaxb应用模式

  在JAVA EE 5\6中,jaxb可以很方便的与jax-rs、jax-ws集成,极大的简化了web service接口的开发工作量

三、jaxb代码举例

  第一步:需要引入javax.xml.bind.jar
  第二步:编写java bean;

package com.mkyong.core; import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement; @XmlRootElementpublic class Customer {  String name; int age; int id;  public String getName() {  return name; }  @XmlElement public void setName(String name) {  this.name = name; }  public int getAge() {  return age; }  @XmlElement public void setAge(int age) {  this.age = age; }  public int getId() {  return id; }  @XmlAttribute public void setId(int id) {  this.id = id; } }

   第三步:main方法把java bean转化为xml字符串

package com.mkyong.core; import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller; public class JAXBExample { public static void main(String[] args) {    Customer customer = new Customer();   customer.setId(100);   customer.setName("mkyong");   customer.setAge(29);    try {   File file = new File("C:\\file.xml");  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();   // output pretty printed  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);   jaxbMarshaller.marshal(customer, file);  jaxbMarshaller.marshal(customer, System.out);        } catch (JAXBException e) {  e.printStackTrace();       }  }}

  下面是输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><customer id="100">    <age>29</age>    <name>mkyong</name></customer>

四、jaxb开发常用

jdk提供了xjc工具可以使xsd自动生成相应的java bean,这大大提高了开发的效率。同时,我们也可以使用trang.jar把xml轻松转化为xsd。下面是使用的举例。

第一步:把数据库表映射为xml

<?xml version="1.0" encoding="UTF-8"?><User u_id="1" u_name="moto" u_email="aaa@XXX.com"  u_mood="今天放假了" u_state="online" u_mobile="12345678901"  u_hometown="山西" u_job="IT软件工程师" u_avatar="w34353453543r53" />

第二步:使用trang.jar转化为xsd文件。在命令行执行:

java -jar D:\lib\trang.jar user.xml user.xsd

下面,是生成的User.java。

//// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.11.13 at 01:26:07 ���� CST //package com.moto.server.bean;import java.math.BigInteger;import javax.xml.bind.annotation.XmlAccessType;import javax.xml.bind.annotation.XmlAccessorType;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.XmlSchemaType;import javax.xml.bind.annotation.XmlType;import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;/** * <p>Java class for anonymous complex type. *  * <p>The following schema fragment specifies the expected content contained within this class. *  * <pre> * <complexType> *   <complexContent> *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> *       <attribute name="u_avatar" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *       <attribute name="u_email" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> *       <attribute name="u_hometown" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *       <attribute name="u_id" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /> *       <attribute name="u_job" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *       <attribute name="u_mobile" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /> *       <attribute name="u_mood" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *       <attribute name="u_name" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *       <attribute name="u_state" use="required" type="{http://www.w3.org/2001/XMLSchema}NCName" /> *     </restriction> *   </complexContent> * </complexType> * </pre> *  *  */@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "")@XmlRootElement(name = "User")public class User {    @XmlAttribute(name = "u_avatar", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uAvatar;    @XmlAttribute(name = "u_email", required = true)    @XmlSchemaType(name = "anySimpleType")    protected String uEmail;    @XmlAttribute(name = "u_hometown", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uHometown;    @XmlAttribute(name = "u_id", required = true)    protected BigInteger uId;    @XmlAttribute(name = "u_job", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uJob;    @XmlAttribute(name = "u_mobile", required = true)    protected BigInteger uMobile;    @XmlAttribute(name = "u_mood", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uMood;    @XmlAttribute(name = "u_name", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uName;    @XmlAttribute(name = "u_state", required = true)    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)    @XmlSchemaType(name = "NCName")    protected String uState;    /**     * Gets the value of the uAvatar property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUAvatar() {        return uAvatar;    }    /**     * Sets the value of the uAvatar property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUAvatar(String value) {        this.uAvatar = value;    }    /**     * Gets the value of the uEmail property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUEmail() {        return uEmail;    }    /**     * Sets the value of the uEmail property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUEmail(String value) {        this.uEmail = value;    }    /**     * Gets the value of the uHometown property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUHometown() {        return uHometown;    }    /**     * Sets the value of the uHometown property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUHometown(String value) {        this.uHometown = value;    }    /**     * Gets the value of the uId property.     *      * @return     *     possible object is     *     {@link BigInteger }     *          */    public BigInteger getUId() {        return uId;    }    /**     * Sets the value of the uId property.     *      * @param value     *     allowed object is     *     {@link BigInteger }     *          */    public void setUId(BigInteger value) {        this.uId = value;    }    /**     * Gets the value of the uJob property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUJob() {        return uJob;    }    /**     * Sets the value of the uJob property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUJob(String value) {        this.uJob = value;    }    /**     * Gets the value of the uMobile property.     *      * @return     *     possible object is     *     {@link BigInteger }     *          */    public BigInteger getUMobile() {        return uMobile;    }    /**     * Sets the value of the uMobile property.     *      * @param value     *     allowed object is     *     {@link BigInteger }     *          */    public void setUMobile(BigInteger value) {        this.uMobile = value;    }    /**     * Gets the value of the uMood property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUMood() {        return uMood;    }    /**     * Sets the value of the uMood property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUMood(String value) {        this.uMood = value;    }    /**     * Gets the value of the uName property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUName() {        return uName;    }    /**     * Sets the value of the uName property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUName(String value) {        this.uName = value;    }    /**     * Gets the value of the uState property.     *      * @return     *     possible object is     *     {@link String }     *          */    public String getUState() {        return uState;    }    /**     * Sets the value of the uState property.     *      * @param value     *     allowed object is     *     {@link String }     *          */    public void setUState(String value) {        this.uState = value;    }}

转载自:https://blog.csdn.net/hfrujhv/article/details/83788497

Jaxb的优点与用法(bean转xml的插件,简化webservice接口的开发工作量)的更多相关文章

  1. 7 -- Spring的基本用法 -- 11... 基于XML Schema的简化配置方式

    7.11 基于XML Schema的简化配置方式 Spring允许使用基于XML Schema的配置方式来简化Spring配置文件. 7.11.1 使用p:命名空间简化配置 p:命名空间不需要特定的S ...

  2. 使用JAXB实现Bean与Xml相互转换

    最近几天,我自己负责的应用这边引入了一个新的合作方,主要是我这边调用他们的接口,但是有个很坑的地方,他们传参居然不支持json格式,并且只支持xml格式进行交互,于是自己写了一个工具类去支持bean与 ...

  3. JAVA bean与XML互转的利器---XStream

    最近在项目中遇到了JAVA bean 和XML互转的需求, 本来准备循规蹈矩使用dom4j忽然想起来之前曾接触过的XStream, 一番研究豁然开朗,利器啊利器, 下来就XStream的一些用法与大家 ...

  4. JAVA Bean和XML之间的相互转换 - XStream简单入门

    JAVA Bean和XML之间的相互转换 - XStream简单入门 背景介绍 XStream的简介 注解简介 应用实例 背景介绍 我们在工作中经常 遇到文件解析为数据或者数据转化为xml文件的情况, ...

  5. java JAXB + STAX(是一种针对XML的流式拉分析API)读取xml

    JDK1.5需要添加jar包,1.6以后就不需要了<dependency> <groupId>stax</groupId> <artifactId>st ...

  6. Spring基础使用(一)--------IOC、Bean的XML方式装配

    基础 1.xml文件基础格式: <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns=&q ...

  7. dom4j+反射实现bean与xml的相互转换

    由于目前在工作中一直用的dom4j+反射实现bean与xml的相互转换,记录一下,如果有不正确的地方欢迎大家指正~~~ 一.反射机制 在此工具类中使用到了反射技术,所以提前也看了一些知识点,例如:ht ...

  8. notepad++ 编辑xml的插件和使用方法

    notepad++ 编辑xml的插件和使用方法.mark http://blog.csdn.net/wangnan537/article/details/48712233

  9. Win 10 开发中Adaptive磁贴模板的XML文档结构,Win10 应用开发中自适应Toast通知的XML文档结构

    分享两篇Win 10应用开发的XML文档结构:Win 10 开发中Adaptive磁贴模板的XML文档结构,Win10 应用开发中自适应Toast通知的XML文档结构. Win 10 开发中Adapt ...

随机推荐

  1. Nginx/Apache + acme.sh 实现https访问

    1 概述 acme.sh实现了acme协议,可以从Let's Encrypt生成免费的ssl证书用于实现https,本文介绍了常见的两种服务器Apache与Nginx上利用acme.sh配置https ...

  2. kube-batch 创建的pod 一直是Pending

    官网的例子 apiVersion: batch/v1 kind: Job metadata: name: qj-1 spec: backoffLimit: 6 completions: 6 paral ...

  3. Day11_54_泛型(Generic)

    泛型 * Java泛型设计原则:只要在编译时期没有出现警告,那么运行时期就不会出现ClassCastException异常. * 泛型:把类型明确的工作推迟到创建对象或调用方法的时候才去明确的特殊的类 ...

  4. 浅谈 C# Assembly 与 IL (一):C# Assembly 与 Reflection

    作者:Compasslg 前言 前一阵子想利用闲余时间写一个 Unity 游戏的翻译工具,主要是用于翻译一些内嵌在代码中的文本,最初想偷懒看了一下网上的教学推荐说可以先利用DnSpy.ILSpy等工具 ...

  5. python 迭代器,生成器,表达式

    1.迭代器 (1)什么是迭代器: #迭代器即迭代的工具,那什么是迭代呢?#迭代是一个重复的过程,每次重复即一次迭代,并且每次迭代的结果都是下一次迭代的初始值 while True: #只是单纯地重复, ...

  6. 通读《构建之法》与CI/CD工具尝试

    项目 内容 这个作业属于哪个课程 2021春季软件工程(罗杰 任健) 这个作业的要求在哪里 作业要求 我在这个课程的目标是 积累软件开发经验,提高工程能力 这个作业在哪个具体方面帮助我实现目标 通读课 ...

  7. shellcode隐写到像素RGB免杀上线到CS

    利用把Shellcode隐写到图片像素RGB进行免杀上线到CS --by:chenw 0x01 前言 前几天跟一个朋友一起搞一个站的时候,发现那个站点开了很多杀软,使用CS的powershell马无法 ...

  8. hdu4496并查集的删边操作

    题意:       给你一个图,问你删除一些边后还有几个连通快.. 思路:       典型的并查集删边操作,并查集的删边就是先把不删除的边并查集一边(本题没有不删除的边),然后逆序吧所有要删除的边以 ...

  9. Bugku-flag.php

    flag.php 目录 flag.php 题目描述 解题过程 题目描述 点了login咋没反应 提示:hint 解题过程 fuzz 打开发现是个登录页面,点击login没反应,看了源码,action= ...

  10. 【js】Leetcode每日一题-完成所有工作的最短时间

    [js]Leetcode每日一题-完成所有工作的最短时间 [题目描述] 给你一个整数数组 jobs ,其中 jobs[i] 是完成第 i 项工作要花费的时间. 请你将这些工作分配给 k 位工人.所有工 ...