jdom的官方git地址:
https://github.com/hunterhacker/jdom
基本用法
实战
写一个xml,并保存到指定的目录中,以xml文件的形式展示:
引入jar包
<dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>2.0.2</version> </dependency>
工具类xmlutil:
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 org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class XMLUtils { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(XMLUtils.class); /** * 将文档写入本地的xml文件中 * @param document * @param name * @return */ public static boolean createXMLFile(Document document, String name) { try { File file = new File(name + ".xml"); XMLOutputter xmlOutputter = new XMLOutputter(); Format format = Format.getRawFormat(); format.setIndent(" "); format.setTextMode(Format.TextMode.TRIM_FULL_WHITE); // document.setDocType( new DocType().setElementName(document.getRootElement())); xmlOutputter.setFormat(format); xmlOutputter.output(document, new FileOutputStream(file)); return true; } catch (IOException e) { logger.error("创建XML出错", e); return false; } } /** * 将json对象,转成xml格式数据 * @param jsonObject * @return */ public static List jsonToXML(JSONObject jsonObject) { List list=new ArrayList<Element>(); jsonObject.entrySet().forEach(i -> { Element element = new Element(i.getKey()); element.setText(i.getValue().toString()); list.add(element); }); return list; } /** * 将map转成xml格式数据 * @param map * @return */ public static List mapToXMl(Map map){ List list=new ArrayList<Element>(); map.forEach((i,v) -> { Element element = new Element(i.toString()); element.setText(v!=null?v.toString():""); list.add(element); }); return list; } /** * 将xml文件解析成document文档 * @param path * @return */ public static Document parseXMLFile(String path) { try { File file = new File(path+".xml"); return new SAXBuilder().build(file); } catch (Exception e) { e.printStackTrace(); logger.error("解析XML出错", e); return null; } } /** * 根据节点属性获取某个文档节点 * @param element * @param id * @return */ public static Element getElementById(Element element, String id) { Element child = null; for (Element item : element.getChildren()) { if (item.getAttributeValue("id").equals(id)) { child = item; } } return child; } }
业务代码:
拷贝不能直接使用,有些是从数据库中读取的内容
public static void creatClothesXmlTest() { /* 创建xml相关的逻辑 */ //创建xml根元素 1.判断文件是否存在,如果存在先删除了,然后创建根元素 // String fileConfigPath = EdgemgmtConfig.getCameraConfigClothesUploadFile() + ".xml"; String fileConfigPath = "D:/cameraConfigClothesUpload"; Boolean isExists = FileUtils.isFileExists(fileConfigPath + ".xml"); Document document = null; if (isExists) { FileUtils.deleteFile(fileConfigPath + ".xml"); } document = new Document(); document.setRootElement(new Element("cameraConfigClothesUpload")); Element rootEle = document.getRootElement(); Element cameraElement = new Element("camera"); cameraElement.setAttribute("id", 1 + ""); Map map = new HashMap<String, Object>() {{ put("cameraId", 1); put("cameraName", "摄像头1"); put("videoStream", "rtsp://admin:jingke1533@192.168.2.4/Streaming/Channels/101?transportmode=unicast&profile=Profile_1"); put("mark", "暂无备注"); }}; //摄像头基础信息转xml cameraElement.addContent(XMLUtils.mapToXMl(map)); cameraElement.addContent(new Element("detectionAlgorithms")); Element detectionAlgorithms = cameraElement.getChild("detectionAlgorithms"); SysCameraAlgorithm sysCameraAlgorithm = new SysCameraAlgorithm(); sysCameraAlgorithm.setId(1L); sysCameraAlgorithm.setAlgorithmName("工服检测"); sysCameraAlgorithm.setTrustValue(0.5D); //告警周期 sysCameraAlgorithm.setWarningInterval(2); //检测周期 sysCameraAlgorithm.setDiscernInterval(2); //运行状态 sysCameraAlgorithm.setRunStatus(1); ZoneId zoneId = ZoneId.of("Asia/Shanghai"); ZonedDateTime zonedDateTime = ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, zoneId); Date startDate = Date.from(zonedDateTime.toInstant()); zonedDateTime = ZonedDateTime.of(1970, 1, 1, 23, 59, 59, 0, zoneId); Date endDate = Date.from(zonedDateTime.toInstant()); sysCameraAlgorithm.setRunStartTime(startDate); sysCameraAlgorithm.setRunEndTime(endDate); sysCameraAlgorithm.setAlgorithmId(29L); SysCameraAlgorithmServiceImpl cameraAlgorithmService = new SysCameraAlgorithmServiceImpl(); //创建算法xml 从数据库中查询获取到算法对象 Element sysCameraAlgorithmConfigElement = cameraAlgorithmService.createConfigElement(sysCameraAlgorithm); //添加算法内容 detectionAlgorithms.addContent(sysCameraAlgorithmConfigElement); //添加摄像头节点 rootEle.addContent(cameraElement); //创建文件 XMLUtils.createXMLFile(document, fileConfigPath); } public static void main(String[] args) { creatClothesXmlTest(); }
查看效果:
D盘已经有了该文件:
具体内容:
大功告成!!!