最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java操作XML轉(zhuǎn)JSON數(shù)據(jù)格式詳細代碼實例

 更新時間:2024年04月07日 08:31:38   作者:楠木知更鳥  
在Java中我們可以使用一些現(xiàn)成的庫來實現(xiàn)XML到JSON的轉(zhuǎn)換,下面這篇文章主要給大家介紹了關(guān)于Java操作XML轉(zhuǎn)JSON數(shù)據(jù)格式的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

一、使用的maven依賴

		<dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>

二、代碼實現(xiàn)

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.dom4j.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.*;


public class XMLParse  {

    //文件路徑
    static String path = "D:\\DevelopWorkspace\\MY\\opensource-framework\\RuoYi-Vue\\doc\\DataSourceConfig.xml";

    public static void main(String[] args) throws Exception {

        //1、讀取文件并轉(zhuǎn)換為Document文檔對象
        Document doc = new SAXReader().read(new File(path));

        //2、使用asXML()方法將DOM文檔對象轉(zhuǎn)換為字符串
        String s = doc.asXML();

        //3、調(diào)用自定義的方法轉(zhuǎn)換為JSON數(shù)據(jù)格式
        JSONObject jsonObject = startXMLToJSON(s);

        //4、輸出結(jié)果
        System.out.println(jsonObject);


    }

    /**
     * 自定義*/
    public static JSONObject startXMLToJSON(String xml){
        //1、定義JSON對象保存結(jié)果
        JSONObject result = new JSONObject();
        try {
            //2、使用DocumentHelper.parseText()轉(zhuǎn)換為DOM文檔對象
            Document document = DocumentHelper.parseText(xml);
            //3、獲取DOM文檔根節(jié)點
            Element rootElement = document.getRootElement();
            //4、調(diào)用自定義的方法轉(zhuǎn)換為JSON數(shù)據(jù)格式
            parseJson(rootElement,result);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void parseJson(Element element,JSONObject result){
        //1、獲取子節(jié)點列表
        List<Element> elements = element.elements();
        //2、循環(huán)子節(jié)點列表獲取數(shù)據(jù)
        for (Element e:elements) {
            //3、有數(shù)據(jù)則獲取
            if (!e.elements().isEmpty() && !e.getText().isEmpty()){
                //4、定義另一個JSON對象保存子節(jié)點JSON數(shù)據(jù)
                JSONObject cjson = new JSONObject();
                //5、此處調(diào)用自身繼續(xù)方法繼續(xù)循環(huán)取值,知道遍歷完所有字節(jié)點數(shù)據(jù)
                parseJson(e,cjson);
                if (!cjson.isEmpty()){
                    //6、添加到JSON對象
                    result.put(e.getName(),cjson);
                }
            }else {
                if (!e.getText().isEmpty()){
                    //6、添加到JSON對象
                    result.put(e.getName(),e.getText());
                }
            }
        }
    }
 }

Debug流程源碼解析

1、SAXReader加載XML文件,創(chuàng)建DOM文檔對象

        //1、讀取文件并轉(zhuǎn)換為Document文檔對象
        Document doc = new SAXReader().read(new File(path));

①、調(diào)用SAXReader.read(File file)方法

闡述:
【注釋意思】:從給定的文件參數(shù)中讀取文檔:
1、file–是要讀取的文件。
2、返回:新創(chuàng)建的Document實例
3、拋出:DocumentException–如果在解析過程中發(fā)生錯誤
【執(zhí)行步驟】:
1、使用new InputSource(new FileInputStream(file))獲取文件輸入流對象source
2、校驗字符編碼,此處并沒有設(shè)置
3、file.getAbsolutePath()獲取文件file的絕對路徑
4、文件路徑path不為空則統(tǒng)一文件路徑的分隔符/
5、最后將文件輸入流對象source作為參數(shù)調(diào)用read(source)方法

	Reads a Document from the given File
	Params:
	file – is the File to read from.
	Returns:
	the newly created Document instance
	Throws:
	DocumentException – if an error occurs during parsing.
	public Document read(File file) throws DocumentException {
        try {
            /*
             * We cannot convert the file to an URL because if the filename
             * contains '#' characters, there will be problems with the URL in
             * the InputSource (because a URL like
             * http://myhost.com/index#anchor is treated the same as
             * http://myhost.com/index) Thanks to Christian Oetterli
             */
             //1、使用new InputSource(new FileInputStream(file))獲取文件輸入流對象source
            InputSource source = new InputSource(new FileInputStream(file));
            
            //2、校驗字符編碼,此處并沒有設(shè)置
            if (this.encoding != null) {
                source.setEncoding(this.encoding);
            }
            //3、file.getAbsolutePath()獲取文件file的絕對路徑
            String path = file.getAbsolutePath();

			//4、文件路徑path不為空則統(tǒng)一文件路徑的分隔符/
            if (path != null) {
                // Code taken from Ant FileUtils
                StringBuffer sb = new StringBuffer("file://");

                // add an extra slash for filesystems with drive-specifiers
                if (!path.startsWith(File.separator)) {
                    sb.append("/");
                }

                path = path.replace('\\', '/');
                sb.append(path);

                source.setSystemId(sb.toString());
            }
            
			//5、最后將文件輸入流對象source作為參數(shù)調(diào)用read(source)方法
            return read(source);
        } catch (FileNotFoundException e) {
            throw new DocumentException(e.getMessage(), e);
        }
    }

②調(diào)用read(InputSource in)方法

闡述:
【注釋意思】:使用SAXParams從給定的InputSource讀取文檔:
1、in–要讀取的InputSource。
2、返回:新創(chuàng)建的Document實例
3、拋出:DocumentException–如果在解析過程中發(fā)生錯誤。

	public Document read(InputSource in) throws DocumentException {
        try {
            XMLReader reader = getXMLReader();

            reader = installXMLFilter(reader);

            EntityResolver thatEntityResolver = this.entityResolver;

            if (thatEntityResolver == null) {
                thatEntityResolver = createDefaultEntityResolver(in
                        .getSystemId());
                this.entityResolver = thatEntityResolver;
            }

            reader.setEntityResolver(thatEntityResolver);

            SAXContentHandler contentHandler = createContentHandler(reader);
            contentHandler.setEntityResolver(thatEntityResolver);
            contentHandler.setInputSource(in);

            boolean internal = isIncludeInternalDTDDeclarations();
            boolean external = isIncludeExternalDTDDeclarations();

            contentHandler.setIncludeInternalDTDDeclarations(internal);
            contentHandler.setIncludeExternalDTDDeclarations(external);
            contentHandler.setMergeAdjacentText(isMergeAdjacentText());
            contentHandler.setStripWhitespaceText(isStripWhitespaceText());
            contentHandler.setIgnoreComments(isIgnoreComments());
            reader.setContentHandler(contentHandler);

            configureReader(reader, contentHandler);

            reader.parse(in);

            return contentHandler.getDocument();
        } catch (Exception e) {
            if (e instanceof SAXParseException) {
                // e.printStackTrace();
                SAXParseException parseException = (SAXParseException) e;
                String systemId = parseException.getSystemId();

                if (systemId == null) {
                    systemId = "";
                }

                String message = "Error on line "
                        + parseException.getLineNumber() + " of document "
                        + systemId + " : " + parseException.getMessage();

                throw new DocumentException(message, e);
            } else {
                throw new DocumentException(e.getMessage(), e);
            }
        }
    }

2、Document使用asXML()方法將DOM文檔對象轉(zhuǎn)換為字符串,該方法繼承接口Node

闡述:
【注釋意思】:
asXML返回該節(jié)點的文本XML表示。
1、返回:此節(jié)點的XML表示形式
2、接口返回數(shù)據(jù)類型:String
3、接口實現(xiàn)類 AbstractDocument
【執(zhí)行步驟】:
1、使用OutputFormat定義輸出XML文件流格式
2、StringWriter作為字符串輸出緩沖區(qū)
3、創(chuàng)建XMLWriter并輸出對象
4、最后返回輸出到StringWriter的字符串

/**
 * <p>
 * <code>asXML</code> returns the textual XML representation of this node.
 * </p>
 * 
 * @return the XML representation of this node
 */
String asXML();
	public String asXML() {
		//1、使用OutputFormat定義輸出XML文件流格式
        OutputFormat format = new OutputFormat();
        
        //2、定義編碼格式,建議使用UTF-8
        format.setEncoding(encoding);
        
        try {
        	//3、創(chuàng)建StringWriter作為字符串輸出緩沖區(qū)
            StringWriter out = new StringWriter();
            
            //4、創(chuàng)建XMLWriter并輸出對象
            XMLWriter writer = new XMLWriter(out, format);
            writer.write(this);
            writer.flush();
            
			//5、最后返回輸出到StringWriter的字符串
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException("IOException while generating textual "
                    + "representation: " + e.getMessage());
        }
    }

2、DocumentHelper.parseText(String text)把字符串轉(zhuǎn)換為DOM對象

闡述:
【注釋意思】:
<code>parseText</code>將給定的文本解析為XML文檔返回新創(chuàng)建的文檔。param 1、text要解析的XML文本
2、返回一個新解析的文檔
2、如果無法解析文檔,則@throws DocumentException
【執(zhí)行步驟】:
1、使用OutputFormat定義輸出XML文件流格式
2、StringWriter作為字符串輸出緩沖區(qū)
3、創(chuàng)建XMLWriter并輸出對象
4、最后返回輸出到StringWriter的字符串

    /**
     * <p>
     * <code>parseText</code> parses the given text as an XML document and
     * returns the newly created Document.
     * </p>
     * 
     * @param text
     *            the XML text to be parsed
     * 
     * @return a newly parsed Document
     * 
     * @throws DocumentException
     *             if the document could not be parsed
     */
    public static Document parseText(String text) throws DocumentException {
        Document result = null;
		//1、創(chuàng)建SAXReader
        SAXReader reader = new SAXReader();
        
		//2、換取編碼格式
        String encoding = getEncoding(text);
        
		//3、使用輸入流讀取需要解析的字符串文本
        InputSource source = new InputSource(new StringReader(text));
        //4、設(shè)置編碼格式
        source.setEncoding(encoding);
		//使用read(InputSource in)方法讀取解析
        result = reader.read(source);

        // if the XML parser doesn't provide a way to retrieve the encoding,
        // specify it manually
        //如果XML解析器不提供檢索編碼的方法,手動指定
        if (result.getXMLEncoding() == null) {
            result.setXMLEncoding(encoding);
        }

        return result;
    }

總結(jié) 

到此這篇關(guān)于Java操作XML轉(zhuǎn)JSON數(shù)據(jù)格式的文章就介紹到這了,更多相關(guān)Java操作XML轉(zhuǎn)JSON內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot自定義Banner使用詳解

    SpringBoot自定義Banner使用詳解

    這篇文章主要介紹了SpringBoot自定義Banner使用詳解,啟動 Spring Boot 時,幾乎總是能在控制臺上方看到如下橫幅,這個也叫字符畫、英文ASCII藝術(shù)字,這就是banner,我們來看一下如何使用,需要的朋友可以參考下
    2024-01-01
  • Java數(shù)據(jù)脫敏常用方法(3種)

    Java數(shù)據(jù)脫敏常用方法(3種)

    數(shù)據(jù)脫敏常用在電話號碼和身份證號,本文主要介紹了Java數(shù)據(jù)脫敏常用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • Java類和成員變量聲明類詳解

    Java類和成員變量聲明類詳解

    這篇文章主要介紹了Java類和成員變量聲明類詳解,類中的成員變量——這些被稱為字段,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-08-08
  • Java實現(xiàn)獲取Excel中的表單控件

    Java實現(xiàn)獲取Excel中的表單控件

    Excel中可通過【開發(fā)工具】菜單欄下插入表單控件,如文本框、單選按鈕、復(fù)選框、組合框等等。本文將利用Java實現(xiàn)獲取Excel中的表單控件,需要的可以參考一下
    2022-05-05
  • SpringBoot整合Shiro的環(huán)境搭建教程

    SpringBoot整合Shiro的環(huán)境搭建教程

    這篇文章主要為大家詳細介紹了SpringBoot整合Shiro的環(huán)境搭建教程,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的小伙伴可以了解一下
    2022-12-12
  • 多個版本JAVA切換的簡單步驟記錄

    多個版本JAVA切換的簡單步驟記錄

    在工作中或者學(xué)習(xí)過程中,有一些特殊情況我們需要來切換java版本來做比較,比如一些新特性等等的相關(guān)資料,這篇文章主要介紹了多個版本JAVA切換的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2024-09-09
  • 為何Java8需要引入新的日期與時間庫

    為何Java8需要引入新的日期與時間庫

    這篇文章主要給大家介紹了關(guān)于Java8為什么需要引入新的日期與時間庫的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • SpringBoot集成Druid實現(xiàn)多數(shù)據(jù)源的兩種方式

    SpringBoot集成Druid實現(xiàn)多數(shù)據(jù)源的兩種方式

    這篇文章主要介紹了SpringBoot集成Druid實現(xiàn)多數(shù)據(jù)源的兩種方式,集成com.baomidou的方式和基于AOP手動實現(xiàn)多數(shù)據(jù)源原生的方式,文中通過代碼示例講解的非常詳細,需要的朋友可以參考下
    2024-03-03
  • maven導(dǎo)入無法拉取所需依賴的解決方法

    maven導(dǎo)入無法拉取所需依賴的解決方法

    最近遇到個問題maven導(dǎo)入無法拉取所需依賴的解決方法,本文就來詳細的介紹一下解決方法,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • Spring MVC整合Kaptcha的具體使用

    Spring MVC整合Kaptcha的具體使用

    Kaptcha 是一個可高度配置的實用驗證碼生成工具,本文主要介紹了Spring MVC整合Kaptcha的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06

最新評論

墨江| 土默特左旗| 武川县| 南宫市| 杭锦后旗| 嘉祥县| 北川| 扎鲁特旗| 大名县| 张北县| 小金县| 西林县| 陵川县| 蓬溪县| 女性| 青阳县| 漳平市| 太和县| 游戏| 北安市| 临夏县| 沅陵县| 贡山| 池州市| 泰和县| 清原| 乌兰浩特市| 方城县| 方城县| 大丰市| 巫溪县| 四会市| 丽水市| 富源县| 延津县| 陇川县| 航空| 三亚市| 宁南县| 汝城县| 灵山县|