您的位置:首页 > Web前端 > JavaScript

批量xml格式文件按字段顺序转json文件

2017-09-27 13:03 148 查看
环境:Eclipse4.4+jdk1.7+Maven3

参考链接:http://blog.csdn.net/jkxqj/article/details/76977280

根据需要略有改动。

package test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.alibaba.fastjson.JSONObject;

public class Xml2JsonUtil {
/**
* 转换一个xml格式的字符串到json格式
* @param xml    xml格式的字符串
* @return 成功返回json 格式的字符串;失败反回null
*/
public static  String xml2JSON(String xml) {
JSONObject obj = new JSONObject();
try {
Inp
4000
utStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
obj.put(root.getName(), iterateElement(root));
return obj.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 转换一个xml格式的字符串到json格式
* @param file     java.io.File实例是一个有效的xml文件
* @return 成功反回json 格式的字符串;失败反回null
*/
public static String xml2JSON(File file) {
JSONObject obj = new JSONObject();
try {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(file);
Element root = doc.getRootElement();
obj.put(root.getName(), iterateElement(root));
return obj.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 一个迭代方法
* @param element
*  org.jdom.Element
* @return java.util.Map 实例
*/
@SuppressWarnings("unchecked")
private static Map  iterateElement(Element element) {
List jiedian = element.getChildren();
Element et = null;
Map obj = new LinkedHashMap();  //LinkedHashMap:是有序的,按xml格式的顺序解析;HashMap:是无序的
List list = null;
for (int i = 0; i < jiedian.size(); i++) {
list = new LinkedList();
et = (Element) jiedian.get(i);
if (et.getTextTrim().equals("")) {
/*            if (et.getChildren().size() == 0)
continue;  */
if (obj.containsKey(et.getName())) {
list = (LinkedList) obj.get(et.getName());
}
list.add(iterateElement(et));
obj.put(et.getName(), list);
} else {
if (obj.containsKey(et.getName())) {
list = (LinkedList) obj.get(et.getName());
}
list.add(et.getTextTrim());
obj.put(et.getName(), list);
}
}
return obj;
}

public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
InputStream is = new FileInputStream(filePath);
String line; // 用来保存每行读取的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine(); // 读取第一行
while (line != null) { // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append("\n"); // 添加换行符
line = reader.readLine(); // 读取下一行
}
reader.close();
is.close();
}

/**
* 读取文本文件内容
* @param filePath 文件所在路径
* @return 文本内容
* @throws IOException 异常
*/
public static String readFile(String filePath) throws IOException {
StringBuffer sb = new StringBuffer();
Xml2JsonUtil.readToBuffer(sb, filePath);
return sb.toString();
}

//写字符串到文件
public static void WriteStringToFile(String filePath,String s) {
try {
File file = new File(filePath);
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.println(s);// 往文件里写入字符串
ps.close();
//ps.append("http://www.docin.com/p-315288370.html");// 在已有的基础上添加字符串
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static void getFile(String path) throws IOException{
File file = new File(path);
File[] array = file.listFiles();
System.out.println("一共"+array.length+"个文件");
for(int i=0;i<array.length;i++){
if(array[i].isFile()){

System.out.println("搜索到文件:" + array[i].getName());
String newName=array[i].getName().substring(0, array[i].getName().indexOf("."))+".json";
String json=Xml2JsonUtil.xml2JSON(Xml2JsonUtil.readFile(array[i]+""));
//因为不需要根节点,所以替换掉了一些字符
json = json.replace("[{}]", "\"\"");
json = json.replace("{\"ROWDATA\":{\"ROW\":[", "");
json = json.replace("]}}", "");
json = json.replace("},{", "}\n{");
json = json.replace("[", "");
json = json.replace("]", "");
Xml2JsonUtil.WriteStringToFile("D:/新json/"+newName,json);
//Xml2JsonUtil.WriteStringToFile("D:/测试json文件/"+newName,json);
}else if(array[i].isDirectory()){
getFile(array[i].getPath());
}
}
}

public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
//创建目录
if (dir.mkdirs()) {
System.out.println("创建目录" + destDirName + "成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}

// 测试
public static void main(String[] args) throws IOException {
//for(int i=1;i<3;i++){

Xml2JsonUtil.createDir("D:/新json文件");//存放json文件的路径
Xml2JsonUtil.getFile("D:/新xml文件/");//遍历该路径下的xml文件
//Xml2JsonUtil.createDir("D:/测试json文件");
//Xml2JsonUtil.getFile("D:/测试xml文件/");
//}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: