Java代码如何实现xml文件和java对象相互转换呢?
下文笔者讲述使用java代码将xml文件和java对象互相转换的方法分享,如下所示
xml工具类的编写
xml格式说明
xml作为一种文件格式 常用于持久化对象操作,因为xml可采用key和属性的方法存储数据 那么xml信息如何和对象之间相互转换呢?下文笔者将一一道来,如下所示
实现思路: 使用hutool的XmlUtil工具 或使用jdom 都可对xml进行操作例:
xml工具类的编写
一、添加pom依赖 <dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency> 二、XmlUtil工具类编写 import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /** * XML工具类 */ public class XmlUtil { /** * JSON对象转成xml文件 * * @param jsonInfo json信息 * @param filePath 文件路径,格式:D:\\file\\demo.xml * @return 是否成功 */ public static boolean jsonToXml(JSONObject jsonInfo, String filePath) throws Exception { File file = new File(filePath); // 创建根元素 Element rootElement = new Element("description").setAttribute("title", FileUtil.getPrefix(filePath)); // 将JSON信息转成Element Element xmlElement = convertObjectToXmlElement(jsonInfo, "xml", rootElement); Document document = new Document(xmlElement); XMLOutputter xmlOut = new XMLOutputter(); Format format = Format.getPrettyFormat(); format.setExpandEmptyElements(true); xmlOut.setFormat(format); try (FileOutputStream filefos = new FileOutputStream(file)) { xmlOut.output(document, filefos); } catch (IOException e) { throw new Exception(StrUtil.format("生成XML文件失败{}", e)); } finally { xmlOut.clone(); } return true; } /** * xml文件转JSON * * @param filePath xml文件 * @return JSONObject * @throws Exception */ public static JSONObject xmlToJson(String filePath) throws Exception { try { File file = new File(filePath); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(file); Element element = document.getRootElement(); Map elementMap = xmlElementToMap(element); return JSON.parseObject(JSON.toJSONString(elementMap)); } catch (Exception e) { throw new Exception(StrUtil.format("解析XML失败,文件地址为【{}】", filePath)); } } /** * 将对象转成xml元素 * * @param json 对象 * @param parentElement 父级元素 */ private static Element convertObjectToXmlElement(Object json, String code, Element parentElement) { Element child; String eleStr; Object childValue; if (json instanceof JSONArray) { JSONArray jsonArray = (JSONArray) json; for (int i = 0; i < jsonArray.size(); i++) { childValue = jsonArray.get(i); child = new Element(code); parentElement.addContent(child); convertObjectToXmlElement(childValue, code, child); } } else if (json instanceof JSONObject) { JSONObject jsonObject = (JSONObject) json; for (Object temp : jsonObject.keySet()) { eleStr = temp.toString(); childValue = jsonObject.get(temp); child = new Element(eleStr); if (childValue instanceof JSONArray) { convertObjectToXmlElement(childValue, eleStr, parentElement); } else { parentElement.addContent(child); convertObjectToXmlElement(childValue, eleStr, child); } } } else if (json instanceof Date) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); parentElement.setText(sf.format((Date) json)); } else { parentElement.setText(json.toString()); } return parentElement; } private static Map xmlElementToMap(Element root) { list childrenList = root.getChildren(); Element element = null; Map map = new HashMap(16); List list = null; for (int i = 0; i < childrenList.size(); i++) { list = new ArrayList(); element = (Element) childrenList.get(i); if (!element.getChildren().isEmpty()) { if (root.getChildren(element.getName()).size() > 1) { if (map.containsKey(element.getName())) { list = (List) map.get(element.getName()); } list.add(xmlElementToMap(element)); map.put(element.getName(), list); } else { map.put(element.getName(), xmlElementToMap(element)); } } else { if (root.getChildren(element.getName()).size() > 1) { if (map.containsKey(element.getName())) { list = (List) map.get(element.getName()); } list.add(element.getTextTrim()); map.put(element.getName(), list); } else { map.put(element.getName(), element.getTextTrim()); } } } return map; }
工具类的测试
public static void main(String[] args) throws Exception { JSONObject jsonObject = JSON.parseObject("{\"A\":[{\"t1\":\"v1\",\"t2\":\"v2\"}]}"); XmlUtil.jsonToXml(jsonObject, "D:\\t1.xml"); JSONObject jsonResult = XmlUtil.xmlToJson("D:\\t1.xml"); System.out.println(jsonResult.toJSONString()); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。