欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

导出xml格式文件

程序员文章站 2022-03-31 16:58:57
...

先定义XML格式
顺序和存放值,都在实体类中限制,如下:

import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-09-03 13:52
 * @Modified By:
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "",propOrder = {
        "clazz"
})
@XmlRootElement(name = "ROOT")
public class ClazzXml {

    @XmlElement(name = "CLAZZ",required = true)
    private List<ClazzXml.CLAZZ> clazz;

    public List<CLAZZ> getClazz() {
        if(clazz==null){
            clazz=new ArrayList<ClazzXml.CLAZZ>();
        }
        return this.clazz;
    }

    public void setClazz(List<CLAZZ> clazz) {
        this.clazz = clazz;
    }

    /**
     *班级xml
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "",propOrder = {
          "csitem",
          "studentitems"
    })
    public static class CLAZZ{

        @XmlElement(name = "CSITEM",required = true)
        private ClazzXml.CLAZZ.CSITEM csitem;
        @XmlElement(name = "STUDENTITEMS",required = true)
        private ClazzXml.CLAZZ.STUDENTITEMS studentitems;


        public CSITEM getCsitem() {
            if(csitem==null){
                csitem=new ClazzXml.CLAZZ.CSITEM();
            }
            return this.csitem;
        }

        public void setCsitem(CSITEM csitem) {
            this.csitem = csitem;
        }

        public STUDENTITEMS getStudentitems() {
            if(studentitems==null){
                studentitems=new ClazzXml.CLAZZ.STUDENTITEMS();
            }
            return this.studentitems;
        }

        public void setStudentitems(STUDENTITEMS studentitems) {
            this.studentitems = studentitems;
        }

        /**
         * 班级信息
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "",propOrder = {
                "csname",
                "csnumber",
                "csaddress",
                "headteacher"

        })
        public static class CSITEM{

            @XmlElement(name = "CSNAME",required = true)
            private String csname;
            @XmlElement(name = "CSNUMBER",required = true)
            private Integer csnumber;
            @XmlElement(name = "CSADDRESS",required = true)
            private String csaddress;
            @XmlElement(name = "HEADTEACHER",required = true)
            private String headteacher;

            public String getCsname() {
                return csname;
            }

            public void setCsname(String csname) {
                this.csname = csname;
            }

            public Integer getCsnumber() {
                return csnumber;
            }

            public void setCsnumber(Integer csnumber) {
                this.csnumber = csnumber;
            }

            public String getCsaddress() {
                return csaddress;
            }

            public void setCsaddress(String csaddress) {
                this.csaddress = csaddress;
            }

            public String getHeadteacher() {
                return headteacher;
            }

            public void setHeadteacher(String headteacher) {
                this.headteacher = headteacher;
            }
        }

        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "",propOrder = {
                "studentitem"
        })
        public static class STUDENTITEMS{
            @XmlElement(name = "STUDENTITEM",required = true)
            private List<ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM> studentitem;

            public List<STUDENTITEM> getStudentitem() {
                if(studentitem==null){
                    studentitem=new ArrayList<ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM>();
                }
                return this.studentitem;
            }

            public void setStudentitem(List<STUDENTITEM> studentitem) {
                this.studentitem = studentitem;
            }

            @XmlAccessorType(XmlAccessType.FIELD)
            @XmlType(name = "",propOrder = {
                    "sid",
                    "sname",
                    "sage",
                    "ssex",
                    "height",
                    "weight",
                    "ranking",
                    "birthday"
            })
            public static class STUDENTITEM{
                @XmlElement(name = "SID",required = true)
                private String sid;
                @XmlElement(name = "SNAME",required = true)
                private String sname;
                @XmlElement(name = "SAGE",required = true)
                private Integer sage;
                @XmlElement(name = "SSEX",required = true)
                private String ssex;
                @XmlElement(name = "HEIGHT",required = true)
                private Double height;
                @XmlElement(name = "WEIGHT",required = true)
                private Double weight;
                @XmlElement(name = "RANKING",required = true)
                private Integer ranking;
                @XmlElement(name = "BIRTHDAY",required = true)
                private String birthday;

                public String getSid() {
                    return sid;
                }

                public void setSid(String sid) {
                    this.sid = sid;
                }

                public String getSname() {
                    return sname;
                }

                public void setSname(String sname) {
                    this.sname = sname;
                }

                public Integer getSage() {
                    return sage;
                }

                public void setSage(Integer sage) {
                    this.sage = sage;
                }

                public String getSsex() {
                    return ssex;
                }

                public void setSsex(String ssex) {
                    this.ssex = ssex;
                }

                public Double getHeight() {
                    return height;
                }

                public void setHeight(Double height) {
                    this.height = height;
                }

                public Double getWeight() {
                    return weight;
                }

                public void setWeight(Double weight) {
                    this.weight = weight;
                }

                public Integer getRanking() {
                    return ranking;
                }

                public void setRanking(Integer ranking) {
                    this.ranking = ranking;
                }

                public String getBirthday() {
                    return birthday;
                }

                public void setBirthday(String birthday) {
                    this.birthday = birthday;
                }
            }

        }


  }

}

快速创建实体类方法类

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-09-03 15:08
 * @Modified By:
 */
public class ClazzFactory {

    public ClazzFactory(){

    }

    public ClazzXml creatROOT(){
        return new ClazzXml();
    }

    public ClazzXml.CLAZZ creatROOTCLAZZ(){
        return new ClazzXml.CLAZZ();
    }
    public ClazzXml.CLAZZ.CSITEM creatROOTCLAZZCSITEM(){
        return new ClazzXml.CLAZZ.CSITEM();
    }

    public ClazzXml.CLAZZ.STUDENTITEMS creatROOTCLAZZSTUDENTITEMS(){
        return new ClazzXml.CLAZZ.STUDENTITEMS();
    }
    public ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM creatROOTCLAZZSTUDENTITEMSSTUDENTITEM(){
        return new ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM();
    }


}

bean对象与XML转换工具类

import javax.xml.bind.*;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-09-03 16:03
 * @Modified By:
 */
public class XmlUtil {
    /**
     * bean2Xml
     *
     * @param bean
     *        要转换成xml的bean对象
     * @param xsdName
     *        生成的xml文件受哪个xsd约束
     *        可以为空
     * @return
     *         生成的xml字符串
     * @throws JAXBException
     */
    public static String bean2Xml(Object bean, String xsdName) throws JAXBException {

        StringWriter stringWriter;
        try {
            JAXBContext context = JAXBContext.newInstance(bean.getClass());

            Marshaller mar = context.createMarshaller();
            stringWriter = new StringWriter();

            // 添加xsd约束
            if (xsdName != null && !"".equals(xsdName)) {
                mar.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, xsdName);
            }

            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            mar.setProperty(Marshaller.JAXB_ENCODING,"UTF-8");
            mar.marshal(bean, stringWriter);

        } catch (PropertyException e) {
            throw e;
        } catch (JAXBException e) {
            throw e;
        }

        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }

    /**
     * bean2Xml
     *
     * @param bean
     *        要转换成xml的bean对象
     * @param filePath
     *        生成文件的全路径(含文件名)
     * @param xsdName
     *        生成的xml文件受哪个xsd约束
     *        可以为空
     * @return
     *         生成的xml字符串
     * @throws JAXBException
     */
    public static void bean2Xml(Object bean, String filePath, String xsdName) throws JAXBException {

        try {
            JAXBContext context = JAXBContext.newInstance(bean.getClass());

            Marshaller mar = context.createMarshaller();

            // 添加xsd约束
            if (xsdName != null && !"".equals(xsdName)) {
                mar.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, xsdName);
            }

            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            mar.setProperty(Marshaller.JAXB_ENCODING,"GBK");
            mar.marshal(bean, new File(filePath));

        } catch (PropertyException e) {
            throw e;
        } catch (JAXBException e) {
            throw e;
        }
    }

    /**
     * xml2Bean
     * 将字符串形式的xml转换成bean
     *
     * @param <T>
     * @param clazz
     * @param xmlString
     * @return javaBean
     * @throws JAXBException
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2Bean(Class<T> clazz, String xmlString) throws JAXBException {
        T result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmar = context.createUnmarshaller();
            StringReader inputStream = new StringReader(xmlString);
            result = (T) unmar.unmarshal(inputStream);
        } catch (JAXBException e) {
            e.printStackTrace();
            throw e;
        }

        return result;
    }

}

测试类,如果导出,需要HttpServletResponse 这里做测试,主要测试xml的生成,导出的方法也有因为是自测的main所以无法实现导出

package com.example.springboot09.com.test;

import com.example.springboot09.com.pojo.ClazzFactory;
import com.example.springboot09.com.pojo.ClazzXml;
import com.example.springboot09.com.util.XmlUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: Administrator
 * @Description:
 * @Date: 2019-09-03 15:22
 * @Modified By:
 */
public class Test3 {

    private static ClazzFactory factory=new ClazzFactory();
    private static ClazzXml root=new ClazzXml();
    private static ClazzXml.CLAZZ clazz=new ClazzXml.CLAZZ();
    private static ClazzXml.CLAZZ.CSITEM csitem=new ClazzXml.CLAZZ.CSITEM();
    private static ClazzXml.CLAZZ.STUDENTITEMS studentitems=new ClazzXml.CLAZZ.STUDENTITEMS();
    private static ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM studentitem=new ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM();

    public static void main(String[] args) {
        HttpServletResponse response=null;
        clazz=factory.creatROOTCLAZZ();
        queryCsItem();//封装班级信息
        queryStudentitems();//封装学生新
        //creatAndSendXML(response);//生成XML response从前台获取的再controller中实现,因为本次实现未再前台页面调用,导出XML的方法 所以response为临时值,主要测试XML数据封装
        try {
            Thread.sleep(10000);
        }catch (Exception e){
            e.printStackTrace();
        }
        creatAndSendXML11();

    }

    public static void queryCsItem(){
        csitem=factory.creatROOTCLAZZCSITEM();
        csitem.setCsname("高一一班");
        csitem.setCsnumber(80);
        csitem.setCsaddress("北院南栋401");
        csitem.setHeadteacher("高一一");
        clazz.setCsitem(csitem);
    }

    public static void queryStudentitems(){
        studentitems=factory.creatROOTCLAZZSTUDENTITEMS();
        //for (){}
        studentitem=factory.creatROOTCLAZZSTUDENTITEMSSTUDENTITEM();
        studentitem.setSid("9001401010101");
        studentitem.setSname("马超");
        studentitem.setSage(16);
        studentitem.setSsex("男");
        studentitem.setHeight(180.0);
        studentitem.setWeight(65.00);
        studentitem.setRanking(1);
        studentitem.setBirthday("2000-01-01");
        studentitems.getStudentitem().add(studentitem);
        ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM  studentitem2=new ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM();
        studentitem2.setSid("9001401010102");
        studentitem2.setSname("赵云");
        studentitem2.setSage(16);
        studentitem2.setSsex("男");
        studentitem2.setHeight(170.0);
        studentitem2.setWeight(60.00);
        studentitem2.setRanking(2);
        studentitem2.setBirthday("2000-01-01");
        studentitems.getStudentitem().add(studentitem2);
        ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM  studentitem3=new ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM();
        studentitem3.setSid("9001401010103");
        studentitem3.setSname("孙尚香");
        studentitem3.setSage(16);
        studentitem3.setSsex("女");
        studentitem3.setHeight(160.0);
        studentitem3.setWeight(48.00);
        studentitem3.setRanking(3);
        studentitem3.setBirthday("2000-01-01");
        studentitems.getStudentitem().add(studentitem3);
        ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM studentitem4=new ClazzXml.CLAZZ.STUDENTITEMS.STUDENTITEM();
        studentitem4.setSid("9001401010104");
        studentitem4.setSname("貂蝉");
        studentitem4.setSage(16);
        studentitem4.setSsex("女");
        studentitem4.setHeight(170.0);
        studentitem4.setWeight(50.00);
        studentitem4.setRanking(4);
        studentitem4.setBirthday("2000-01-01");
        studentitems.getStudentitem().add(studentitem4);

        clazz.setStudentitems(studentitems);
        root.getClazz().add(clazz);
    }
    /**
     * 测试xml
     */
    public static void creatAndSendXML11(){
        String xml = "";
        try {
           xml=XmlUtil.bean2Xml(root,"");
            System.out.println(xml);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 导出xml 需要HttpServletResponse response
     */
    public static void creatAndSendXML(HttpServletResponse response){
        String xml = "";
        BufferedOutputStream output = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-msdownload");
            xml = XmlUtil.bean2Xml(root,"");
            System.out.println("XML--->"+root);
            response.addHeader("Content-Disposition","attachment;filename=CLAZZ"+date+"90014010101"+".xml");
            output = new BufferedOutputStream(response.getOutputStream());
            output.write(xml.getBytes());
            output.flush();   //不可少
            response.flushBuffer();//不可少
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                output.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}

导出结果如下

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ROOT>
    <CLAZZ>
        <CSITEM>
            <CSNAME>高一一班</CSNAME>
            <CSNUMBER>80</CSNUMBER>
            <CSADDRESS>北院南栋401</CSADDRESS>
            <HEADTEACHER>高一一</HEADTEACHER>
        </CSITEM>
        <STUDENTITEMS>
            <STUDENTITEM>
                <SID>9001401010101</SID>
                <SNAME>马超</SNAME>
                <SAGE>16</SAGE>
                <SSEX>男</SSEX>
                <HEIGHT>180.0</HEIGHT>
                <WEIGHT>65.0</WEIGHT>
                <RANKING>1</RANKING>
                <BIRTHDAY>2000-01-01</BIRTHDAY>
            </STUDENTITEM>
            <STUDENTITEM>
                <SID>9001401010102</SID>
                <SNAME>赵云</SNAME>
                <SAGE>16</SAGE>
                <SSEX>男</SSEX>
                <HEIGHT>170.0</HEIGHT>
                <WEIGHT>60.0</WEIGHT>
                <RANKING>2</RANKING>
                <BIRTHDAY>2000-01-01</BIRTHDAY>
            </STUDENTITEM>
            <STUDENTITEM>
                <SID>9001401010103</SID>
                <SNAME>孙尚香</SNAME>
                <SAGE>16</SAGE>
                <SSEX>女</SSEX>
                <HEIGHT>160.0</HEIGHT>
                <WEIGHT>48.0</WEIGHT>
                <RANKING>3</RANKING>
                <BIRTHDAY>2000-01-01</BIRTHDAY>
            </STUDENTITEM>
            <STUDENTITEM>
                <SID>9001401010104</SID>
                <SNAME>貂蝉</SNAME>
                <SAGE>16</SAGE>
                <SSEX>女</SSEX>
                <HEIGHT>170.0</HEIGHT>
                <WEIGHT>50.0</WEIGHT>
                <RANKING>4</RANKING>
                <BIRTHDAY>2000-01-01</BIRTHDAY>
            </STUDENTITEM>
        </STUDENTITEMS>
    </CLAZZ>
</ROOT>

相关标签: java