Dom4j的简单使用小记

元素(Element)和结点(Node)有区别,节点包含了元素,元素一定是节点,而必须是含有完整信息的结点才是一个元素。

即元素必须是例如<div>...</div>这样的,而节点可以是一个空行。

it is safe to cast Node returned from selectNodes() or selectSingleNodes() to Element if you are sure that XPath expression returns element(s). 

Depending on XPath it can return Element, Attribute, Text etc. So if you hope your Xpath returns Elements only, it is safe to cast. If you are not sure, you should check type before cast.


使用root.selectNodes("srcfile[@name='" + changedFile + "']");时抛出异常

java.lang.NoClassDefFoundError: org/jaxen/JaxenExc

原因:没有导入jaxen 包

/* Parse emma report
 * <srcfile name="TransactionConsts.java">
 *		<coverage type="class, %" value="0%   (0/1)"/>
 *		<coverage type="method, %" value="0%   (0/1)"/>
 *		<coverage type="block, %" value="0%   (0/3)"/>
 *		<coverage type="line, %" value="0%   (0/1)"/>
 */


File xmlFile = new File(emmaReportPath);
SAXReader reader = new SAXReader();
Document document = reader.read(xmlFile);
Element root = document.getRootElement();
List srcfileNodeList = root.selectNodes("//srcfile");
for(String changedFile : changedFileList){
	for (Object o : srcfileNodeList) {
		Element srcfileElement = (Element)o;
		if(changedFile.equals(srcfileElement.attributeValue("name"))){
		Element targetElement = (Element)srcfileElement.selectSingleNode("coverage[@type='line, %']);
		String coverageValue = targetElement.attributeValue("value");
		if("".equals(coverageValue))
				continue;
		fileCoverageMap.put(changedFile, coverageValue);
		break;
		}
	}
}

xpath

表达式 描述 
节点名 选择所有该名称的节点集 
/ 选择根节点 
// 选择当前节点下的所有节点 
. 选择当前节点 
.. 选择父节点 
@ 选择属性 
示例 
表达式            描述 
bookstore 选择所有bookstore子节点 
/bookstore 选择根节点bookstore 
bookstore/book 在bookstore的子节点中选择所有名为book的节点 
//book          选择xml文档中所有名为book的节点 
bookstore//book 选择节点bookstore下的所有名为book为节点 
//@lang          选择所有名为lang的属性 
断言 
在方括号中[],用来更进一步定位选择的元素 
表达式                      描述 
/bookstore/book[1]          选择根元素bookstore的book子元素中的第一个 
注意: IE5以上浏览器中第一个元素是0 
/bookstore/book[last()] 选择根元素bookstore的book子元素中的最后一个 
/bookstore/book[last()-1] 选择根元素bookstore的book子元素中的最后第二个 
/bookstore/book[position()<3] 选择根元素bookstore的book子元素中的前两个 
//title[@lang]          选择所有拥有属性lang的titile元素 
//title[@lang='eng'] 选择所有属性值lang为eng的title元素 
/bookstore/book[price>35.00] 选择根元素bookstore的book子元素中那些拥有price子元素且值大于35的 
/bookstore/book[price>35.00]/title 选择根元素bookstore的book子元素中那些拥有price子元素且值大于35的title子元素 
选择位置的节点 
通配符               描述 
*             匹配所有元素 
@*             匹配所有属性节点 
node()             匹配任何类型的节点 
示例 
表达式               描述 
/bookstore/*    选择根元素bookstore的下的所有子元素 
//*             选择文档中所有元素 
//title[@*]    选择所有拥有属性的title元素 

使用操作符“|”组合选择符合多个path的表达式 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章