xml json 互转功能实现
引用的包
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedHashMap;
import java.util.List;
@Component
public class TestXml2Json {
private static final Logger logger = LoggerFactory.getLogger(TestXml2Json.class);
public static void main(String[] args) throws Exception {
String xmlStr = readFile("E://backup//DeskTop//CaliConfig.xml");
String xmlFile = "E://backup//DeskTop//json2xml.xml";
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject(new LinkedHashMap<>());
xml2json(doc.getRootElement(), json);
JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
jsonObject.put(doc.getRootElement().getName(), json);
System.out.println(jsonObject.toJSONString());
// 创建一个Document实例
Document writeDoc = DocumentHelper.createDocument();
Element element = writeDoc.addElement(doc.getRootElement().getName());
json2Xml(json, element);
createDom4j(new File(xmlFile), writeDoc);
}
public static String readFile(String path) throws Exception {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
//fc向buffer中读入数据
fc.read(bb);
bb.flip();
String str = new String(bb.array(), "UTF8");
fc.close();
fis.close();
return str;
}
/**
* xml转json
*
* @param element
* @param json
*/
public static void xml2json(Element element, JSONObject json) {
//如果是属性
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("-" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !isEmpty(element.getText())) {//如果没有子元素,只有一个值
json.put("#text", element.getText());
}
for (Element e : chdEl) {//有子元素
JSONObject chdjson = new JSONObject(new LinkedHashMap<>());
xml2json(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
}
}
public static boolean isEmpty(String str) {
if (str == null || str.trim().isEmpty() || "null".equals(str)) {
return true;
}
return false;
}
/**
* json2xml
*
* @param json
* @param element
*/
public static void json2Xml(JSONObject json, Element element) {
for (String key : json.keySet()) {
if (key.startsWith("-")) {
element.addAttribute(key.replace("-", ""), json.getString(key));
} else if (key.equals("#text")) {
element.addText(json.getString(key));
} else {
Object o = json.get(key);
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {
Element child = element.addElement(key);
json2Xml(json.getJSONObject(key), child);
} else if (o instanceof JSONArray) {
if (!json.getJSONArray(key).isEmpty()) {
jsonArray2Xml(json.getJSONArray(key), element, key);
}
} else if (o instanceof String) {
element.addText(json.getString(key));
}
}
}
}
}
/***
* jsonArray2Element
* @param jsonArray
* @param element
* @param rootName
*/
public static void jsonArray2Xml(JSONArray jsonArray, Element element, String rootName) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Element element1 = element.addElement(rootName);
json2Xml(jsonObject, element1);
}
}
public static void createDom4j(File file, Document doc) throws IOException {
// 创建一个Document实例
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
// xml格式化样式
// OutputFormat format = OutputFormat.createPrettyPrint(); // 默认样式
// 自定义xml样式
OutputFormat format = new OutputFormat();
format.setIndentSize(4); // 行缩进
format.setNewlines(true); // 一个结点为一行
format.setTrimText(true); // 去重空格
format.setPadText(true);
format.setNewLineAfterDeclaration(false); // 放置xml文件中第二行为空白行
// 输出xml文件
XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
writer.write(doc);
logger.info("dom4j CreateDom4j success!");
}
}