xml轉bean+xml解析工具類實現 -- Java


手頭正好需要一個xml轉bean的工具和xml解析工具,網上實現很多,自己造一次輪子,一整套流程直接復制可用,一分鍾實現轉換加解析(xml轉換使用idea實現,eclipse同樣有工具,一搜一大把這里就不贅述了)。本文可轉載,標注來源即可。

1.xml轉xsd

1.1樣例XML(persons.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<Persons>
    <person id="1" races="yellow">
        <name type=""></name>
        <age></age>
        <sex></sex>
        <height></height>
        <location>
            <home>china</home>
            <company></company>
        </location>
    </person>
    <person id="2" races="red">
        <name type=""></name>
        <age></age>
        <sex></sex>
        <height></height>
        <location>
            <home>earth</home>
            <company></company>
        </location>
    </person>
    <feature total="">
        <action id=""></action>
        <source type="org">investigation</source>
    </feature>
</Persons>

1.2 利用idea將persons.xml生成persons.xsd

1.2.1首先打開persons.xml文件,右擊點擊Generate XSD Schema from XML File…

首先打開xml文件,右擊點擊Generate XSD Schema from XML File...

1.2.2 生成persons.xsd設置

需要注意Design type選項要選擇local elements/types,確保在xsd轉換bean時保證屬性一致。
生成xsd設置

1.2.3生成persons.xsd文件

生成的persons.xsd文件預覽
在這里插入圖片描述

2.xsd轉JavaBean

2.1 選中person.xsd idea導航欄 [TOOL]>[JAXB]>Generate Java Code From XML Schema Using JAXB…

轉換操作步驟

2.2 person.xsd轉bean設置

屬性Package Prefix設置你需要的bean對象類的存放包路徑,其他屬性不需要調整。
person.xsd轉bean設置

2.3 生成bean

設置完成后會生成如下結構的java類,此時persons.xml轉換bean已經完成
在這里插入圖片描述

2.4 備注

如過生成后發現有參數需要修改,那么我們只需修改persons.xml文件,將過程重新走一遍,相關的persons.xsd以及生成的bean類會自動覆蓋更新。

3.xml解析實現代碼

直接貼代碼,直接復制可用。

3.1 XmlParser工具類實現

package util.xml;

import util.bean.Person;
import util.bean.Persons;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.List;

/** * xml工具類 * * @author sssuperMario * @date 2020/08/28 */
public class XmlParser {
    
    
    public static void main(String[] args) {
        Persons persons = xmlToBean(new File("/IdeaProjects/Persons.xml"), Persons.class);
        System.out.println("person feature[source]:" + persons.getFeature().getSource().getValue());
        List<Person> personList = persons.getPerson();
        for (Person person : personList) {
            System.out.println("person id:" + person.getId() + "\trace:"
                    + person.getRaces() + "\thome:"
                    + person.getLocation().getHome());
        }
    }


    /** * xml to bean * @param xmlFile * @param beanClass * @param <T> * @return */
    public static <T> T xmlToBean(File xmlFile, Class<T> beanClass) {
        if (xmlFile.length() == 0) {
            throw new RuntimeException("xml file content length is blank.");
        }
        BufferedReader bufferedReader = null;
        FileReader fileReader = null;
        StringBuffer content = new StringBuffer();
        try {
            fileReader = new FileReader(xmlFile);
            bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line);
            }
        } catch (Exception e) {
            throw new RuntimeException("xml file read error.", e);
        } finally {
            try {
                fileReader.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return xmlToBean(content.toString(), beanClass);
    }

    /** * xml to bean * @param xmlContent * @param beanClass * @param <T> * @return */
    public static <T> T xmlToBean(String xmlContent, Class<?> beanClass) {
        Reader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(beanClass);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xmlContent);
            return (T) unmarshaller.unmarshal(reader);
        } catch (Exception e) {
            throw new RuntimeException("xml parse error.", e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

3.2 XmlParser工具類運行測試結果

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM