在平时经常遇到需要把xml文件转换为json格式数据的需求,这里将实现读取指定目录的xml文件并吧内容转换为json格式然后输出到指定目录。项目采用spring boot项目,下面是实现的主要步骤:
一,创建一个spring boot项目
1,创建好spring boot项目,配置pom.xml文件,代码如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.szkingdom</groupId>
- <artifactId>xmltojson</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>xmltojson</name>
- <description>Demo project for Spring Boot</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.9.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.33</version>
- </dependency>
- <dependency>
- <groupId>org.json</groupId>
- <artifactId>json</artifactId>
- <version>20171018</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <finalName>xmltojson</finalName>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
上面主要引入一些依赖的jar包,比较简单,就不详细说明了。
注意:
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.6</java.version>
- </properties>
指定java.version为1.6
2,配置application.
- input.dir.filename=F:\\mystudy\\dd_address.xml
- output.dir.filename=F:\\mystudy\\jack.json
- encoding.format=gb2312
二,主要代码
- package com.szkingdom;
- import org.json.XML;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.w3c.dom.Document;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.transform.OutputKeys;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamResult;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.StringWriter;
- import java.net.MalformedURLException;
- import java.net.URL;
- @SpringBootApplication
- public class XmltojsonApplication implements CommandLineRunner {
- //输入文件所在位置
- @Value("${input.dir.filename}")
- private String inputFileName;
- //输出文件所在位置
- @Value("${output.dir.filename}")
- private String outputFileName;
- //xml的编码格式
- @Value("${encoding.format}")
- private String encodingFormat;
- public static void main(String[] args) {
- SpringApplication.run(XmltojsonApplication.class,args);
- }
- @Override
- public void run(String... strings) throws Exception {
- readXml(inputFileName);
- }
- public void readXml(String dir) throws MalformedURLException {
- File f = new File(dir);
- if (!f.exists()) {
- System.out.println("xml文件转换为json文件失败,读取的文件不存在......,请修读取文件配置");
- return;
- }
- URL url = f.toURL();
- System.out.println("读取文件的路径:url = " + url);
- String file = url.getFile();
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- try {
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(file);
- String xml = toStringFromDoc(doc);
- //System.out.println(xml);
- xmlToJson(xml);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 把一个xml的document转换为xml字符串
- *
- * @param document
- * @return
- */
- public String toStringFromDoc(Document document) {
- String result = null;
- if (document != null) {
- StringWriter strWtr = new StringWriter();
- StreamResult strResult = new StreamResult(strWtr);
- TransformerFactory tfac = TransformerFactory.newInstance();
- try {
- javax.xml.transform.Transformer t = tfac.newTransformer();
- //t.setOutputProperty(OutputKeys.ENCODING,"UTF-16");
- //t.setOutputProperty(OutputKeys.ENCODING,"gb2312");
- t.setOutputProperty(OutputKeys.ENCODING,encodingFormat);
- t.setOutputProperty(OutputKeys.INDENT,"yes");
- t.setOutputProperty(OutputKeys.METHOD,"xml"); // xml,html,// text
- t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
- t.transform(new DOMSource(document.getDocumentElement()),strResult);
- } catch (Exception e) {
- System.err.println("XML.toString(Document): " + e);
- }
- result = strResult.getWriter().toString();
- try {
- strWtr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return result;
- }
- /**
- * xml字符串转json字符串
- *
- * @param xml
- */
- public void xmlToJson(String xml) {
- /* 第一种方法,使用JSON-JAVA提供的方法 */
- //将xml转为json
- org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml);
- //设置缩进
- String jsonPrettyPrintString = xmlJSONObj.toString(4);
- //输出格式化后的json
- System.out.println(jsonPrettyPrintString);
- //JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonPrettyPrintString);
- //System.out.println("jsonObject:"+jsonObject);
- //outJsonToFile(jsonObject);
- outJsonToFile(jsonPrettyPrintString);
- }
- /**
- * 输出json字符串到文件
- *
- * @param jsonObject
- */
- public void outJsonToFile(String jsonObject) {
- byte[] buff = new byte[]{};
- //String jsonStr = jsonObject.toJSONString();
- String jsonStr = jsonObject;
- FileOutputStream out = null;
- File file = new File(outputFileName);
- // 检测是否存在目录,不存在则创建目录
- if (!file.getParentFile().exists()) {
- file.getParentFile().mkdirs();
- }
- try {
- buff = jsonStr.getBytes();
- //out=new FileOutputStream(outputFileName);
- out = new FileOutputStream(file);
- System.out.println("输出文件目录:" + outputFileName);
- out.write(buff,buff.length);
- System.out.println("输出json数据到文件成功");
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
使用maven打包项目,使用如下的xmlToJson.bat脚本启动:
- title xmlToJson工具
- f:
- cd F:\mystudy
- java -jar xmltojson.jar --input.dir.filename=F:\\mystudy\\dd_address.xml --output.dir.filename=F:\\mystudy\\dd_address.json --encoding.format=gb2312
- pause
- ::说明:
- ::第一步,切换到xmltojson.jar包所在的目录
- ::第二部,执行xmltojson.jar包,参数说明:
- :: input.dir.filename->输入的xml文件所在的目录文件
- :: output.dir.filename->输出的json文件所在的目录文件
- :: encoding.format->xml文件的编码和输出的json文件的编码,json文件编码采用的是xml文件的编码,默认gb2312
- ::注意:需要安装好了jdk,配置好了java的环境变量
注意如果需要指定jdk启动,修改bat脚本如下:
- title xmlToJson工具
- f:
- cd F:\mystudy
- 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
- pause
- ::说明:
- ::第一步,切换到xmltojson.jar包所在的目录
- ::第二部,执行xmltojson.jar包,参数说明:
- :: input.dir.filename->输入的xml文件所在的目录文件
- :: output.dir.filename->输出的json文件所在的目录文件
- :: encoding.format->xml文件的编码和输出的json文件的编码,json文件编码采用的是xml文件的编码,默认gb2312
- ::注意:需要安装好了jdk,配置好了java的环境变量
主要是,F:\mystudy\jdk1.6\bin\java,指定jdk版本执行jar包