首先以spring的配置文件applicationContext.xml为例:
package cn.itcast.dom4j;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.junit.Test;
public class NamespaceParseXml {
@Test
public void getSingleValue() {
SAXReader reader = new SAXReader();
try {
Document document = reader.read(new File("src/persistence.xml"));
Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
// 设置一个命名空间,其中put中的key可任意取名(符合Java命名规范),value为一个uri;
nsMap.put("key", "http://java.sun.com/xml/ns/persistence");
// 创建一个xpath表达式,xmlns为上面设置的key;两者必须相同;否则会报错;xpath表达式参看文档;
XPath xPath = document
.createXPath("//key:persistence//key:persistence-unit//key:properties//key:property");
// 将设置好的命名空间集合交给xpath对象,使其内部和文档进行匹配和解析;
xPath.setNamespaceURIs(nsMap);
// 用匹配好的名称空间的xpath表达式选取所需的节点做进一步的操作;
String value = xPath.selectSingleNode(document).getText();
System.out.println(value);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
// 使用xpath和namespace进行文档的快速查找,查找出applicationContext.xml文档中;
// 所有id属性值;并打印输出;
@Test
public void getAllId() throws DocumentException {
// 1 创建SAXReader;
SAXReader reader = new SAXReader();
// 通过解析器解析出xml文档对应的文档对象Docment;
Document document = reader.read("src/applicationContext.xml");
// 设置命名空间;
Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
nsMap.put("xmlns", "http://www.springframework.org/schema/beans");
// 创建xpath表达式,并将该表达式封装成XPath对象;
XPath xPath = document.createXPath("//@id");
// 实际上这里可以不用nsMap, 为创建xpath表达式时没有用到名称空间namespace;
xPath.setNamespaceURIs(nsMap);
// 用封装好的xpath对象表达式去搜索文档对象中需要的东西;
List<Attribute> nodes = xPath.selectNodes(document);
for (Attribute attribute : nodes) {
System.out
.println(attribute.getName() + "=" + attribute.getValue());
}
}
@Test
public void getAllBean() {
try {
// 通过解析器获取xml对应的Document对象;
SAXReader reader = new SAXReader();
Document document = reader.read("src/applicationContext.xml");
// 创建名称空间的集合;
Map<String, String> nsMap = new ConcurrentHashMap<String, String>();
nsMap.put("xmlns", "