1. 程式人生 > >批量xml格式檔案按欄位順序轉json檔案

批量xml格式檔案按欄位順序轉json檔案

環境: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
{ InputStream 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檔案/"); //} } }