1 引用dom4j
package com.dom4j.demo;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
public class Dom4jParser {
public static void main(String[] args) throws Exception {
dom4jXpath("mysql");
}
/**
* dom4j常規方式解析 -> 使用命名空間方式解析
* @throws Exception
*/
private static void dom4j() throws Exception {
// 創建SaxReader對象
SAXReader reader = new SAXReader();
InputStream in = Dom4jParser.class.getClassLoader().getResourceAsStream("datasource.xml");
// 獲取到文檔對象
Document document = reader.read(in);
// 獲取根元素對象
Element rootElement = document.getRootElement();
// System.out.println(rootElement);
// 獲取根元素下面所有子元素
// List<Element> elements = rootElement.elements();
// 獲取根元素下面指定元素名稱的子元素集合
List<Element> elements = rootElement.elements("dataSource");
for (Element el : elements) {
System.out.println(el.attributeValue("id") + "-----" + el.attributeValue("class"));
// 獲取el元素下面所有子元素
List<Element> childList = el.elements("property");
for (Element childEl : childList) {
String name = childEl.attributeValue("name");
String text = childEl.getTextTrim();
System.out.println(name + "----------" + text);
}
System.out.println("------------------------------------------");
}
}
/**
* dom4j方式解析使用XPath
* @throws Exception
*/
private static void dom4jXpath(String dataSourceId) throws Exception {
// 創建SaxReader對象
SAXReader reader = new SAXReader();
InputStream in = Dom4jParser.class.getClassLoader().getResourceAsStream("datasource.xml");
// 獲取到文檔對象
Document document = reader.read(in);
XPath xpath = document.createXPath("dataSources/dataSource[@id='"+dataSourceId+"']");
Element dataSourceNode = (Element) xpath.selectSingleNode(document);
System.out.println(dataSourceNode.attributeValue("id")+"----"+dataSourceNode.attributeValue("class"));
xpath = document.createXPath("property");
List<Element> propList = xpath.selectNodes(dataSourceNode);
for (Element el : propList) {
String name = el.attributeValue("name");
String text = el.getTextTrim();
System.out.println(name+"--------------"+text);
}
}
}