Dom4j文档:https://www.oschina.net/uploads/doc/dom4j-1.6.1/index.html
中文文档: https://blog.csdn.net/zys_1997/article/details/78566706
引入依赖
<!-- dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
解析xml格式如下
<?xml version="1.0" encoding="UTF-8"?> <root> <!-- 定时任务表 --> <tasks> <task id="1" taskName="定时任务一" methodName="method1" state="0" className="com.icanits.common.task.TestTask"> <id>1</id> <taskName>定时任务一</taskName> </task> <task id="0c686f79-e64e-4dab-b91b-5a6dcfb07f6b" taskName="定时任务2" methodName="test2" className="com.czy" state="0"> <id>2</id> <taskName>定时任务2</taskName> </task> </tasks> </root>
解析xml字符串
@Test public void tt() throws DocumentException { String xmlStr="<?xml version="1.0" encoding="UTF-8"?> " + " " + "<root> " + " <!-- 定时任务表 --> " + " <tasks> " + " <task id="1" taskName="定时任务一" methodName="method1" state="0" className="com.icanits.common.task.TestTask"> " + " <id>1</id> " + " <taskName>定时任务一</taskName> " + " </task> " + " <task id="0c686f79-e64e-4dab-b91b-5a6dcfb07f6b" taskName="定时任务2" methodName="test2" className="com.czy" state="0"> " + " <id>2</id> " + " <taskName>定时任务2</taskName> " + " </task> " + " </tasks> " + "</root>"; Document document = DocumentHelper.parseText(xmlStr); Element rootElement = document.getRootElement();// 获取根节点 System.out.println("根节点名称: "+rootElement.getName()); Element tasks = rootElement.element("tasks"); // 获取tasks节点 List<Element> elements = tasks.elements();// 获取 tasks下的所有子节点 for (Element element : elements) { String id = element.selectSingleNode("./id").getText(); String taskName = element.selectSingleNode("./taskName").getText(); System.out.println(taskName+" === "+id); } }