使用JAXB进行JavaBean对象与XML文件的相互转化

2023-11-10 02:10

本文主要是介绍使用JAXB进行JavaBean对象与XML文件的相互转化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

思想:父标签相当于一个对象,子标签相当于对象的属性,然后循环嵌套

JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。

Marshaller接口,将Java对象序列化为XML数据。

Unmarshaller接口,将XML数据反序列化为Java对象。

如果是第一次使用的话,建议先下载代码跑一下看看效果:https://download.csdn.net/download/kunfd/10684654

一、注解:

1.@XmlElement(name=””):

指定一个字段或get/set方法映射到XML的节点(注解在方法上)。

2.@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)

定义映射这个类中的何种类型需要映射到XML。可接收四个参数,分别是(注解在类上):

2.1.XmlAccessType. NONE:

所有字段或属性都不能绑定到 XML,除非使用一些 JAXB 注释专门对它们进行注释。被这个注解的类,如果你想类中的属性编入到Xml文件中,必须在对应的属性get/set方法上添加@XmlElement

2.2.XmlAccessType.PUBLIC_MEMBER:

(默认)每个公共获取方法/设置方法对和每个公共字段将会自动绑定到 XML,除非由 XmlTransient 注释。被XmlTransient注解以后就不编入Xml文件中。如果使用默认且在类属性中使用@XmlElement 注解,那么会出现数据重复编入Xml情况。

2.3. XmlAccessType.FIELD:

JAXB 绑定类中的每个非静态、非瞬态字段将会自动绑定到 XML,除非由 XmlTransient 注释。

2.4. XmlAccessType.PROPERTY:

JAXB 绑定类中的每个获取方法/设置方法对将会自动绑定到 XML,除非由 XmlTransient 注释。

3.@XmlElementWrapper(name=””):

在原来封装的基础上,再封装一个(加多一层)name,这里要求被注解的属性必须是集合属性。

4.@XmlType(propOrder={“A”,”B”,”C”}) (注解在类上):

对要编入Xml的类属性进行进行排序,注意,这里的ABC指的是JavaBean类属性实体,也就是  A  a   中的a。而不是@XmlElement

()里面所指的对象

二、配置

1.Marshaller.set(Marshaller.JAXB_ENCODING,”GBK”) :

设置格式为GBK。设置以后,xml文件头的encoding会显示为GBK

2.Marshaller.set(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,”fem.shema.xsd”):

设置非命名空间:

<WH000411 xsi:noNamespaceSchemaLocation="fem.schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

3.如果拥有多个命名空间的话,使用package-info.java包级别的注解

<?xml version="1.0" encoding="UTF-8" standalone="no"?><GzeportTransfer xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:n1="http://www.altova.com/samplexml/other-namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

具体如下:在GzeportTransfer对象同级包下新建一个package-info.java(这个文件一般是创建包的时候一同创建,后期无法直接创建,要的话可以直接在桌面创建一个,然后将附件进来),package-info.java文件的内容如下:注意,注解是在包上面,且无需其他代码

@XmlSchema(

                   xmlns={

                                     @XmlNs(prefix="n1",namespaceURI="http://www.altova.com/samplexml/other-namespace"),

                                     @XmlNs(prefix="ds",namespaceURI="http://www.w3.org/2000/09/xmldsig#"),

                                     @XmlNs(prefix="xsi",namespaceURI="http://www.w3.org/2001/XMLSchema-instance")

                   }

)

/*这里由于是包级别的注解,所以要独立成立一个包,避免影响其他*/

package com.ceb.gztradeio.bo.namespace;

import javax.xml.bind.annotation.*;

注意:该方法必须为JDK1.7如果为JDK1.6的话,那么必须添加两个jar包,分别为jaxb-core-2.2.7.jar和jaxb-impl-2.2.7.jar

https://download.csdn.net/download/kunfd/10684613

三、简单例子

Bean对象

Student对象

package com.test.Jaxb;

import java.util.List;

import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlAttribute;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlElementWrapper;

@XmlAccessorType(XmlAccessType.NONE)

public class Student {

         java.lang.String name;//姓名

         String sex;//性别

         int number;//学号

         String className;//班级

         Set<String> hobby;//爱好

         public Student(String name, String sex, int number, String className,

                            Set<String> hobby) {

                   super();

                   this.name = name;

                   this.sex = sex;

                   this.number = number;

                   this.className = className;

                   this.hobby = hobby;

         }

         public Student() {

         }

         @XmlAttribute(name="name")

         public java.lang.String getName() {

                   return name;

         }

         public void setName(java.lang.String name) {

                   this.name = name;

         }

         @XmlElement(name="sex")

         public String getSex() {

                   return sex;

         }

         public void setSex(String sex) {

                   this.sex = sex;

         }

         @XmlAttribute(name="number")

         public int getNumber() {

                   return number;

         }

         public void setNumber(int number) {

                   this.number = number;

         }

         @XmlElement(name="ClassName")

         public String getClassName() {

                   return className;

         }

         public void setClassName(String className) {

                   this.className = className;

         }

         @XmlElementWrapper(name="bobbys")

         @XmlElement(name="hobby")

         public Set<String> getHobby() {

                   return hobby;

         }

         public void setHobby(Set<String> hobby) {

                   this.hobby = hobby;

         }

         @Override

         public String toString() {

                   return "Student [name=" + name + ", sex=" + sex + ", number=" + number

                                     + ", className=" + className + ", hobby=" + hobby + "]";

         }

        

         //对于拥有get/set方法的属性,注解不能定义在属性的定义上,只能在get或者set上定义一个就可以,否则出错。

}

List对象

package com.test.Jaxb;

import java.util.List;

import java.util.Set;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="List")

public class StudentList {

         Set<Student> students;//所有学生信息集合

        

         @XmlElement(name = "student")

         public Set<Student> getStudents() {

                   return students;

         }

         public void setStudents(Set<Student> students) {

                   this.students = students;

         }

}

 

1.JavaBean转化为XML

package com.test.Jaxb;

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.StringWriter;

import java.util.ArrayList;

import java.util.HashSet;

import java.util.LinkedHashSet;

import java.util.List;

import java.util.Set;

 

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Marshaller;

 

public class StudentToXML {

         public static String beantoXml(Object obj,Class<?> load) throws JAXBException{

                   JAXBContext context = JAXBContext.newInstance(load);

                   Marshaller marshaller = context.createMarshaller();

                   marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");

                   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                   marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "fem.schema.xsd");

                   StringWriter writer = new StringWriter();

                   marshaller.marshal(obj, writer);

                   return writer.toString();

         }

         public static void main(String[] args) throws JAXBException, IOException{

                   Set<String> hobby = new LinkedHashSet<String>();

                   hobby.add("狼求");

                   hobby.add("yingyue");

                   hobby.add("pingpanqiu");//添加body对象

                  

                   Set<Student> studentList = new LinkedHashSet<Student>();

 

                   Student st1 = new Student("张三","娜娜",1001,"尖子班",hobby);

                   studentList.add(st1);

                   Student st2 = new Student("lisi","男",1002,"普通版",hobby);

                   studentList.add(st2);

                   Student st3 = new Student("王五","女",1003,"普通版",hobby);

                   studentList.add(st3);//添students对象

                  

                   StudentList students = new StudentList();

                   students.setStudents(studentList);

                   String str = StudentToXML.beantoXml(students, StudentList.class);

                  

                   String xmlPath="D:/testConfig.xml";

                   BufferedWriter bfw = new BufferedWriter(new FileWriter(new File(xmlPath)));

                   bfw.write(str);

                   bfw.close();

         }

}

生成的结果如下

<?xml version="1.0" encoding="GBK" standalone="yes"?>

<List xsi:noNamespaceSchemaLocation="fem.schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <student number="1001" name="张三">

        <ClassName>尖子班</ClassName>

        <bobbys>

            <hobby>狼求</hobby>

            <hobby>yingyue</hobby>

            <hobby>pingpanqiu</hobby>

        </bobbys>

        <sex>娜娜</sex>

    </student>

    <student number="1002" name="lisi">

        <ClassName>普通版</ClassName>

        <bobbys>

            <hobby>狼求</hobby>

            <hobby>yingyue</hobby>

            <hobby>pingpanqiu</hobby>

        </bobbys>

        <sex>男</sex>

    </student>

    <student number="1003" name="王五">

        <ClassName>普通版</ClassName>

        <bobbys>

            <hobby>狼求</hobby>

            <hobby>yingyue</hobby>

            <hobby>pingpanqiu</hobby>

        </bobbys>

        <sex>女</sex>

    </student>

</List>

 

2.将xml内容转化为对象

package com.test.Jaxb;

 

import java.io.File;

import java.util.Iterator;

 

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

 

public class XmlToStudent {

         public static void main(String[] args){

                   String filepath = "D:/testConfig.xml";

                   StudentList students = xmlToJavabean(filepath, StudentList.class);

                   System.out.println(students.getStudents());

         }

         public static <T> T xmlToJavabean(String filepath,Class<T> c){

                   T t = null;

                   try {

                            File xmlFile = new File(filepath);

                            JAXBContext context = JAXBContext.newInstance(c);

                            Unmarshaller unmarshaller = context.createUnmarshaller();

                            t = (T)unmarshaller.unmarshal(xmlFile);;

                   } catch (JAXBException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                   }

                   return t;

         }

}

结果如下

[Student [name=王五, sex=女, number=1003, className=普通版, hobby=[狼求, pingpanqiu, yingyue]], Student [name=张三, sex=娜娜, number=1001, className=尖子班, hobby=[狼求, pingpanqiu, yingyue]], Student [name=lisi, sex=男, number=1002, className=普通版, hobby=[狼求, pingpanqiu, yingyue]]]

 

这篇关于使用JAXB进行JavaBean对象与XML文件的相互转化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/379791

相关文章

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直