依赖jar

        <dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

JsonXmlUtils.java

package javax.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.Paths; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; /**
* JSON对象与XML相互转换工具类
*
* @author Logan
* @createDate 2019-02-12
* @version 1.0.0
*
*/
public class JsonXmlUtils { private static final String ENCODING = "UTF-8"; /**
* JSON对象转漂亮的xml字符串
*
* @param json JSON对象
* @return 漂亮的xml字符串
* @throws IOException
* @throws SAXException
*/
public static String jsonToPrettyXml(JSONObject json) throws IOException, SAXException {
Document document = jsonToDocument(json); /* 格式化xml */
OutputFormat format = OutputFormat.createPrettyPrint(); // 设置缩进为4个空格
format.setIndent(" ");
format.setIndentSize(4); StringWriter formatXml = new StringWriter();
XMLWriter writer = new XMLWriter(formatXml, format);
writer.write(document); return formatXml.toString();
} /**
* JSON对象转xml字符串
*
* @param json JSON对象
* @return xml字符串
* @throws SAXException
*/
public static String JsonToXml(JSONObject json) throws SAXException {
return jsonToDocument(json).asXML();
} /**
* JSON对象转Document对象
*
* @param json JSON对象
* @return Document对象
* @throws SAXException
*/
public static Document jsonToDocument(JSONObject json) throws SAXException {
Document document = DocumentHelper.createDocument();
document.setXMLEncoding(ENCODING); // root对象只能有一个
for (String rootKey : json.keySet()) {
Element root = jsonToElement(json.getJSONObject(rootKey), rootKey);
document.add(root);
break;
}
return document;
} /**
* JSON对象转Element对象
*
* @param json JSON对象
* @param nodeName 节点名称
* @return Element对象
*/
public static Element jsonToElement(JSONObject json, String nodeName) {
Element node = DocumentHelper.createElement(nodeName);
for (String key : json.keySet()) {
Object child = json.get(key);
if (child instanceof JSONObject) {
node.add(jsonToElement(json.getJSONObject(key), key));
} else {
Element element = DocumentHelper.createElement(key);
element.setText(json.getString(key));
node.add(element);
}
} return node;
} /**
* XML字符串转JSON对象
*
* @param xml xml字符串
* @return JSON对象
* @throws DocumentException
*/
public static JSONObject xmlToJson(String xml) throws DocumentException {
JSONObject json = new JSONObject(); SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(xml));
Element root = document.getRootElement(); json.put(root.getName(), elementToJson(root)); return json;
} /**
* Element对象转JSON对象
*
* @param element Element对象
* @return JSON对象
*/
public static JSONObject elementToJson(Element element) {
JSONObject json = new JSONObject();
for (Object child : element.elements()) {
Element e = (Element) child;
if (e.elements().isEmpty()) {
json.put(e.getName(), e.getText());
} else {
json.put(e.getName(), elementToJson(e));
}
} return json;
} /**
* 文件内容转换成字符串
*
* @param filePath 文件路径
* @return 内容字符串
* @throws IOException
*/
public static String fileToString(URL filePath) throws IOException {
return IOUtils.toString(filePath, ENCODING);
} /**
* 文件内容转换成字符串
*
* @param filePath 文件路径
* @return 内容字符串
* @throws IOException
*/
public static String fileToString(String filePath) throws IOException {
return IOUtils.toString(Paths.get(filePath).toUri(), ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param filePath 文件路径
* @throws IOException
*/
public static void stringToFile(String str, String filePath) throws IOException {
FileUtils.writeStringToFile(Paths.get(filePath).toFile(), str, ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param filePath 文件路径
* @throws IOException
*/
public static void stringToFile(String str, URL filePath) throws IOException {
FileUtils.writeStringToFile(new File(filePath.getPath()), str, ENCODING);
} /**
* 字符串输出到文件
*
* @param str 字符串内容
* @param file 输出文件
* @throws IOException
*/
public static void stringToFile(String str, File file) throws IOException {
FileUtils.writeStringToFile(file, str, ENCODING);
} public static void main(String[] args) {
try {
String filePath = "/User.xml";
URL url = JsonXmlUtils.class.getResource(filePath);
String content = JsonXmlUtils.fileToString(url);
// System.out.println(content); JSONObject json = xmlToJson(content);
System.out.println(JSON.toJSONString(json, true)); String xml = JsonToXml(json);
System.out.println(xml); System.out.println("----------------------------------------\n\n");
xml = jsonToPrettyXml(json);
System.out.println(xml); stringToFile(xml, "G:\\Temp\\Test\\User.xml");
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
} }

测试文件

User.xml

<?xml version="1.0" encoding="UTF-8"?>
<entity>
<user>
<id>1001</id>
<username>Logan</username>
<password>666666</password>
<age>16</age>
</user>
<order>
<id>2001</id>
<price>9.99</price>
<date>2019-02-12</date>
</order>
</entity>

.

最新文章

  1. WCF 安全性 之 Windows
  2. DFS HDOJ 2181 哈密顿绕行世界问题
  3. by maintaining a log containing a record of each transaction’s activities - The Commit/Rollback Protocol
  4. poj1244Slots of Fun
  5. APP store 审核注意点
  6. JS动态广告浏览
  7. 【转】itunes connect 如何修改主要语言
  8. android系统自带图标集合(android.R.drawable查看)
  9. SQL Server 地理数据库中的系统表
  10. AFNetworking3.0 POST请求
  11. Xcode中lldb的REPL调试方法
  12. git 创建SSH key
  13. TOP100summit:【分享实录-华为】微服务场景下的性能提升最佳实践
  14. Unity3D学习笔记(三十八):VR开发
  15. centos6.5 系统乱码解决 i18n --摘自http://blog.csdn.net/yangkai_hudong/article/details/19033393
  16. 百度图片http://img[0-9]\.imgtn.*?g此形式的链接图片下载方式
  17. tomcat如何正确的开启远程调试功能
  18. ajax分页查询
  19. 喵哈哈村的魔法考试 Round #2 (Div.2) 题解
  20. hdoj1003 DP

热门文章

  1. Vue.js递归组件实现动态树形菜单
  2. HTML5 video 连续播放视频
  3. 安装Office 2013 时提示找不到 Office.zh-cn\OfficeLR.cab
  4. entity framework discriminator error
  5. [PHP]AES加密----PHP服务端和Android客户端
  6. web相关知识
  7. js面向对象之属性
  8. Fluent API配置
  9. 合并Gridview单元格
  10. DO、PO、BO、DTO、VO等概念