读取xml文件转换为json文件

前端之家收集整理的这篇文章主要介绍了读取xml文件转换为json文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在平时经常遇到需要把xml文件转换为json格式数据的需求,这里将实现读取指定目录的xml文件并吧内容转换为json格式然后输出到指定目录。项目采用spring boot项目,下面是实现的主要步骤:


一,创建一个spring boot项目

1,创建好spring boot项目,配置pom.xml文件代码如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.szkingdom</groupId>
  7. <artifactId>xmltojson</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10.  
  11. <name>xmltojson</name>
  12. <description>Demo project for Spring Boot</description>
  13.  
  14. <parent>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-parent</artifactId>
  17. <version>1.5.9.RELEASE</version>
  18. <relativePath/> <!-- lookup parent from repository -->
  19. </parent>
  20.  
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  24. <java.version>1.8</java.version>
  25. </properties>
  26.  
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter</artifactId>
  31. </dependency>
  32.  
  33. <dependency>
  34. <groupId>com.alibaba</groupId>
  35. <artifactId>fastjson</artifactId>
  36. <version>1.2.33</version>
  37. </dependency>
  38.  
  39. <dependency>
  40. <groupId>org.json</groupId>
  41. <artifactId>json</artifactId>
  42. <version>20171018</version>
  43. </dependency>
  44.  
  45.  
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52.  
  53. <build>
  54. <finalName>xmltojson</finalName>
  55. <plugins>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62.  
  63.  
  64. </project>

上面主要引入一些依赖的jar包,比较简单,就不详细说明了。

注意:

如果需要指定jdk打包的版本,修改下面的代码

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  4. <java.version>1.6</java.version>
  5. </properties>

指定java.version为1.6


2,配置application.

  1. input.dir.filename=F:\\mystudy\\dd_address.xml
  2. output.dir.filename=F:\\mystudy\\jack.json
  3. encoding.format=gb2312

二,主要代码

  1. package com.szkingdom;
  2.  
  3. import org.json.XML;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.boot.CommandLineRunner;
  6. import org.springframework.boot.SpringApplication;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8. import org.w3c.dom.Document;
  9.  
  10. import javax.xml.parsers.DocumentBuilder;
  11. import javax.xml.parsers.DocumentBuilderFactory;
  12. import javax.xml.transform.OutputKeys;
  13. import javax.xml.transform.TransformerFactory;
  14. import javax.xml.transform.dom.DOMSource;
  15. import javax.xml.transform.stream.StreamResult;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.io.StringWriter;
  20. import java.net.MalformedURLException;
  21. import java.net.URL;
  22.  
  23. @SpringBootApplication
  24. public class XmltojsonApplication implements CommandLineRunner {
  25.  
  26. //输入文件所在位置
  27. @Value("${input.dir.filename}")
  28. private String inputFileName;
  29. //输出文件所在位置
  30. @Value("${output.dir.filename}")
  31. private String outputFileName;
  32. //xml的编码格式
  33. @Value("${encoding.format}")
  34. private String encodingFormat;
  35.  
  36. public static void main(String[] args) {
  37. SpringApplication.run(XmltojsonApplication.class,args);
  38. }
  39.  
  40. @Override
  41. public void run(String... strings) throws Exception {
  42. readXml(inputFileName);
  43. }
  44.  
  45. public void readXml(String dir) throws MalformedURLException {
  46. File f = new File(dir);
  47. if (!f.exists()) {
  48. System.out.println("xml文件转换为json文件失败,读取的文件不存在......,请修读取文件配置");
  49. return;
  50. }
  51. URL url = f.toURL();
  52. System.out.println("读取文件的路径:url = " + url);
  53. String file = url.getFile();
  54. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  55. try {
  56. DocumentBuilder db = dbf.newDocumentBuilder();
  57. Document doc = db.parse(file);
  58. String xml = toStringFromDoc(doc);
  59. //System.out.println(xml);
  60. xmlToJson(xml);
  61. } catch (Exception e) {
  62. e.printStackTrace();
  63. }
  64. }
  65.  
  66. /**
  67. * 把一个xml的document转换为xml字符串
  68. *
  69. * @param document
  70. * @return
  71. */
  72. public String toStringFromDoc(Document document) {
  73. String result = null;
  74. if (document != null) {
  75. StringWriter strWtr = new StringWriter();
  76. StreamResult strResult = new StreamResult(strWtr);
  77. TransformerFactory tfac = TransformerFactory.newInstance();
  78. try {
  79. javax.xml.transform.Transformer t = tfac.newTransformer();
  80. //t.setOutputProperty(OutputKeys.ENCODING,"UTF-16");
  81. //t.setOutputProperty(OutputKeys.ENCODING,"gb2312");
  82. t.setOutputProperty(OutputKeys.ENCODING,encodingFormat);
  83. t.setOutputProperty(OutputKeys.INDENT,"yes");
  84. t.setOutputProperty(OutputKeys.METHOD,"xml"); // xml,html,// text
  85. t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
  86. t.transform(new DOMSource(document.getDocumentElement()),strResult);
  87. } catch (Exception e) {
  88. System.err.println("XML.toString(Document): " + e);
  89. }
  90. result = strResult.getWriter().toString();
  91. try {
  92. strWtr.close();
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. return result;
  98. }
  99.  
  100. /**
  101. * xml字符串转json字符串
  102. *
  103. * @param xml
  104. */
  105. public void xmlToJson(String xml) {
  106. /* 第一种方法,使用JSON-JAVA提供的方法 */
  107. //将xml转为json
  108. org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml);
  109. //设置缩进
  110. String jsonPrettyPrintString = xmlJSONObj.toString(4);
  111. //输出格式化后的json
  112. System.out.println(jsonPrettyPrintString);
  113. //JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonPrettyPrintString);
  114. //System.out.println("jsonObject:"+jsonObject);
  115. //outJsonToFile(jsonObject);
  116. outJsonToFile(jsonPrettyPrintString);
  117. }
  118.  
  119. /**
  120. * 输出json字符串到文件
  121. *
  122. * @param jsonObject
  123. */
  124. public void outJsonToFile(String jsonObject) {
  125. byte[] buff = new byte[]{};
  126. //String jsonStr = jsonObject.toJSONString();
  127. String jsonStr = jsonObject;
  128. FileOutputStream out = null;
  129. File file = new File(outputFileName);
  130. // 检测是否存在目录,不存在则创建目录
  131. if (!file.getParentFile().exists()) {
  132. file.getParentFile().mkdirs();
  133. }
  134. try {
  135. buff = jsonStr.getBytes();
  136. //out=new FileOutputStream(outputFileName);
  137. out = new FileOutputStream(file);
  138. System.out.println("输出文件目录:" + outputFileName);
  139. out.write(buff,buff.length);
  140. System.out.println("输出json数据到文件成功");
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. } finally {
  144. if (out != null) {
  145. try {
  146. out.close();
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. }
  150. }
  151. }
  152. }
  153.  
  154. }



使用maven打包项目,使用如下的xmlToJson.bat脚本启动:

  1. title xmlToJson工具
  2. f:
  3. cd F:\mystudy
  4. java -jar xmltojson.jar --input.dir.filename=F:\\mystudy\\dd_address.xml --output.dir.filename=F:\\mystudy\\dd_address.json --encoding.format=gb2312
  5.  
  6. pause
  7.  
  8. ::说明:
  9. ::第一步,切换到xmltojson.jar包所在的目录
  10. ::第二部,执行xmltojson.jar包,参数说明:
  11. :: input.dir.filename->输入的xml文件所在的目录文件
  12. :: output.dir.filename->输出json文件所在的目录文件
  13. :: encoding.format->xml文件的编码和输出json文件的编码,json文件编码采用的是xml文件的编码,默认gb2312
  14. ::注意:需要安装好了jdk,配置好了java的环境变量


注意如果需要指定jdk启动,修改bat脚本如下:

  1. title xmlToJson工具
  2. f:
  3. cd F:\mystudy
  4. F:\mystudy\jdk1.6\bin\java -jar xmltojson.jar --input.dir.filename=F:\\mystudy\\dd_address.xml --output.dir.filename=F:\\mystudy\\dd_address.json --encoding.format=gb2312
  5.  
  6. pause
  7.  
  8. ::说明:
  9. ::第一步,切换到xmltojson.jar包所在的目录
  10. ::第二部,执行xmltojson.jar包,参数说明:
  11. :: input.dir.filename->输入的xml文件所在的目录文件
  12. :: output.dir.filename->输出json文件所在的目录文件
  13. :: encoding.format->xml文件的编码和输出json文件的编码,json文件编码采用的是xml文件的编码,默认gb2312
  14. ::注意:需要安装好了jdk,配置好了java的环境变量


主要是,F:\mystudy\jdk1.6\bin\java,指定jdk版本执行jar包

猜你在找的XML相关文章