使用dom4j解析xml

作者:哈哈小脸 | 创建时间: 2023-07-09
Java工程师经常要解析xml,dom4j为我们提供了很好的方法...
使用dom4j解析xml

操作方法

新建一个xml

编写java文件 package parseXML; import java.io.File; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * * * @author wb-lilei.u * @version $Id: Demo.java, v 0.1 2015年11月24日 上午10:54:21 wb-lilei.u Exp $ */ public class Demo { public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); File file = new File("D:/workspaces/fcbuservice/autoconf/auto-config.xml"); Document document = reader.read(file); Element root = document.getRootElement(); List<Element> childElements = root.elements(); for (Element child : childElements) { //未知属性名情况下 //已知属性名情况下 //            System.out.println("id: " + child.attributeValue("name")); //未知子元素名情况下 List<Element> elementList = child.elements(); for (Element ele : elementList) { if (ele.attributeValue("name") != null) { if (ele.attributeValue("name").equals("web_root")) { System.out.println(ele.attributeValue("name") + " = " + "${app_root}/release/run/webroot"); } else { System.out.println(ele.attributeValue("name") + " = " + ele.attributeValue("defaultValue")); } } } //            System.out.println(); //已知子元素名的情况下 //            System.out.println("title" + child.elementText("title")); //            System.out.println("author" + child.elementText("author")); //这行是为了格式化美观而存在 System.out.println(); } } }

温馨提示

我测试使用的是jdk1.7+dom4j-1.6.1.jar
点击展开全文

更多推荐