使用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]]]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值