dom4j 块数查找节点(非遍历方式)

 

使用下面这种方式能够直接根据节点的关系查找到节点,然后访问里面的值或者属性

package com.hb;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.xml.sax.SAXException;

public class Dom4jReadXml {

	/**
	 * 随机的获取节点,即指明节点就能得到相关数据
	 */
	@Test
	public void RandomReadNode(){
		
		SAXReader  saxReader = new SAXReader();
		String filePath = "d:/AppProperty.xml";
		File file = new File(filePath);
		try {
			
			Document document = saxReader.read(file);
			//使用这种方式读取节点需要导入jaxen.jar包
			List list = document.selectNodes("/result/value/no");
			Iterator it = list.iterator();
			
			while(it.hasNext()){
				Node node = (Node)it.next();
				System.out.println(node.getText());
			}
			
			System.out.println(document.selectNodes("value").size());
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

 备注:如果想要上面的方法运行正确,除了需要引入dom4j.jar还需要jaxen.jar包

 

package adtec.util.account;

import java.io.File;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import adtec.util.XMLProperties;

public class ABC {

	/**
<?xml version="1.0" encoding="UTF-8"?>
<rootNode>
	<jdbcUserProvider>
		<class>执行认证类的class,这个利用反射来找到该类,并操作数据库</class>
		<pojoClass>指明查询的结果集转换的类</pojoClass>
		<driver>驱动类</driver>
		<connection>连接DB的数据库的账号和密码</connection>
		<tablename>查询的表明</tablename>
		<accountIdField>账号的主键</accountIdField>
		<usernameField>指明用户名</usernameField>
		<passwordField>指明密码</passwordField>
	</jdbcUserProvider>
</rootNode>
	 */
	public static void main(String[] args) {
		String pathStr = "D:/JavaProject/myspring/src/adtec/util/test.xml";
		File file = new File(pathStr);
		try {
			SAXReader xmlReader = new SAXReader();
            xmlReader.setEncoding("UTF-8");
            Document document = xmlReader.read(file);
//            System.out.println(document.asXML());
            //root 节点是rootNode
            Element element = document.getRootElement();
            System.out.println(element.asXML());
//            System.out.println(element.getText());
            //显示xml的path,这里是/rootNode
            System.out.println(element.getUniquePath());
            //显示xml的path,这里是/rootNode/jdbcUserProvider
            System.out.println(element.element("jdbcUserProvider").getUniquePath());
            //如果不是叶子节点,则getText()方法的值为空
            System.out.println(element.element("jdbcUserProvider").element("class").getText());
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

 备注:上面这个例子强调rootElement代表的具体节点,以及element(String)的使用方法

你可能感兴趣的:(dom4j)