java 使用 dom4j 解析xml 文件

首先需要导入 dom4j-1.6.1.jar,以下是测试类。

public class TestDom4j {
	public static void main(String[] args) throws Exception {
		String path = TestDom4j.class.getClassLoader().getResource("student.xml").getFile();

		// 读取整个xml文件到document
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(path));
		
		// 遍历根节点
		Element rootNode = document.getRootElement();
		listNodes(rootNode);
		
		// 修改属性并保存
		rootNode.addAttribute("test", "123123213213213");
		rootNode.attribute("count").setValue("3"); // 同setText
		writeDocument(document);
	}

	@SuppressWarnings("unchecked")
	private static void listNodes(Element node) {
		// 输出节点的文本内容
		System.out.println(node.getName() + " : " + node.getText());

		// 获取所有属性和属性值
		List<Attribute> attributes = node.attributes();
		for (Attribute attribute : attributes) {
			System.out.println(attribute.getName() + " : " + attribute.getValue());
		}

		// 遍历子节点
		Iterator<Element> iterator = node.elementIterator();
		while (iterator.hasNext()) {
			Element chilrd = iterator.next();
			listNodes(chilrd);
		}
	}

	private static void writeDocument(Document document) throws Exception {
		// OutputFormat format = OutputFormat.createCompactFormat(); // 紧凑型,不格式化
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		
		FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/test.xml"));
		OutputStreamWriter streamWriter = new OutputStreamWriter(fileOutputStream);
		XMLWriter xmlWriter = new XMLWriter(streamWriter, format);

		xmlWriter.write(document);
		xmlWriter.flush();
		xmlWriter.close();
		streamWriter.close();
		fileOutputStream.close();
	}
}

  

 

参考例子:http://www.fengyunxiao.cn

posted @ 2018-07-24 14:15  亦寒2017  阅读(121)  评论(1编辑  收藏  举报