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的表達式 


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