Java操作XML轉(zhuǎn)JSON數(shù)據(jù)格式詳細(xì)代碼實(shí)例
一、使用的maven依賴
<dependency> <groupId>org.dom4j</groupId> <artifactId>dom4j</artifactId> <version>2.1.3</version> </dependency>
二、代碼實(shí)現(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文檔對(duì)象 Document doc = new SAXReader().read(new File(path)); //2、使用asXML()方法將DOM文檔對(duì)象轉(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對(duì)象保存結(jié)果 JSONObject result = new JSONObject(); try { //2、使用DocumentHelper.parseText()轉(zhuǎn)換為DOM文檔對(duì)象 Document document = DocumentHelper.parseText(xml); //3、獲取DOM文檔根節(jié)點(diǎn) 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é)點(diǎn)列表 List<Element> elements = element.elements(); //2、循環(huán)子節(jié)點(diǎn)列表獲取數(shù)據(jù) for (Element e:elements) { //3、有數(shù)據(jù)則獲取 if (!e.elements().isEmpty() && !e.getText().isEmpty()){ //4、定義另一個(gè)JSON對(duì)象保存子節(jié)點(diǎn)JSON數(shù)據(jù) JSONObject cjson = new JSONObject(); //5、此處調(diào)用自身繼續(xù)方法繼續(xù)循環(huán)取值,知道遍歷完所有字節(jié)點(diǎn)數(shù)據(jù) parseJson(e,cjson); if (!cjson.isEmpty()){ //6、添加到JSON對(duì)象 result.put(e.getName(),cjson); } }else { if (!e.getText().isEmpty()){ //6、添加到JSON對(duì)象 result.put(e.getName(),e.getText()); } } } } }
Debug流程源碼解析
1、SAXReader加載XML文件,創(chuàng)建DOM文檔對(duì)象
//1、讀取文件并轉(zhuǎn)換為Document文檔對(duì)象 Document doc = new SAXReader().read(new File(path));
①、調(diào)用SAXReader.read(File file)方法
闡述:
【注釋意思】:從給定的文件參數(shù)中讀取文檔:
1、file–是要讀取的文件。
2、返回:新創(chuàng)建的Document實(shí)例
3、拋出:DocumentException–如果在解析過程中發(fā)生錯(cuò)誤
【執(zhí)行步驟】:
1、使用new InputSource(new FileInputStream(file))獲取文件輸入流對(duì)象source
2、校驗(yàn)字符編碼,此處并沒有設(shè)置
3、file.getAbsolutePath()獲取文件file的絕對(duì)路徑
4、文件路徑path不為空則統(tǒng)一文件路徑的分隔符/
5、最后將文件輸入流對(duì)象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))獲取文件輸入流對(duì)象source InputSource source = new InputSource(new FileInputStream(file)); //2、校驗(yàn)字符編碼,此處并沒有設(shè)置 if (this.encoding != null) { source.setEncoding(this.encoding); } //3、file.getAbsolutePath()獲取文件file的絕對(duì)路徑 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、最后將文件輸入流對(duì)象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實(shí)例
3、拋出:DocumentException–如果在解析過程中發(fā)生錯(cuò)誤。
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文檔對(duì)象轉(zhuǎn)換為字符串,該方法繼承接口Node
闡述:
【注釋意思】:
asXML返回該節(jié)點(diǎn)的文本XML表示。
1、返回:此節(jié)點(diǎn)的XML表示形式
2、接口返回?cái)?shù)據(jù)類型:String
3、接口實(shí)現(xiàn)類 AbstractDocument
【執(zhí)行步驟】:
1、使用OutputFormat定義輸出XML文件流格式
2、StringWriter作為字符串輸出緩沖區(qū)
3、創(chuàng)建XMLWriter并輸出對(duì)象
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并輸出對(duì)象 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對(duì)象
闡述:
【注釋意思】:
<code>parseText</code>將給定的文本解析為XML文檔返回新創(chuàng)建的文檔。param 1、text要解析的XML文本
2、返回一個(gè)新解析的文檔
2、如果無法解析文檔,則@throws DocumentException
【執(zhí)行步驟】:
1、使用OutputFormat定義輸出XML文件流格式
2、StringWriter作為字符串輸出緩沖區(qū)
3、創(chuàng)建XMLWriter并輸出對(duì)象
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解析器不提供檢索編碼的方法,手動(dòng)指定 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解Java中的HashMap的實(shí)現(xiàn)機(jī)制
這篇文章主要介紹了深入理解Java中的HashMap的實(shí)現(xiàn)機(jī)制,同時(shí)也有助于理解Java中對(duì)于哈希函數(shù)的相關(guān)處理方式,需要的朋友可以參考下2015-07-07BeanUtils.copyProperties()所有的空值不復(fù)制問題
這篇文章主要介紹了BeanUtils.copyProperties()所有的空值不復(fù)制問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06Java后臺(tái)處理Json格式數(shù)據(jù)的方法
這篇文章主要介紹了Java后臺(tái)處理Json格式數(shù)據(jù)的方法的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06Spring Boot 應(yīng)用程序中配置使用consul的方法
配置是 Spring Boot 應(yīng)用程序中的一部分,主要用于配置服務(wù)端口、應(yīng)用名稱、Consul 服務(wù)發(fā)現(xiàn)以及健康檢查等功能,下面給大家介紹Spring Boot 應(yīng)用程序中配置使用consul,感興趣的朋友一起看看吧2025-04-04Java中的三種校驗(yàn)注解的使用(@Valid,@Validated和@PathVariable)
本文主要介紹了Java中的三種校驗(yàn)注解的使用(@Valid,@Validated和@PathVariable),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04Spring Boot命令行運(yùn)行器的實(shí)現(xiàn)方法
這篇文章主要介紹了Spring Boot命令行運(yùn)行器的實(shí)現(xiàn)方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-10-10Spring Data Neo4j實(shí)現(xiàn)復(fù)雜查詢的多種方式
在 Spring Data Neo4j 中,實(shí)現(xiàn)復(fù)雜查詢可以通過多種方式進(jìn)行,包括使用自定義查詢、方法命名查詢以及使用 Cypher 查詢語(yǔ)言,以下是詳細(xì)介紹,幫助你在 Spring Data Neo4j 中實(shí)現(xiàn)復(fù)雜查詢,需要的朋友可以參考下2024-11-11