dom4j解析XML時使用XPath直接定位至標籤例項
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;
publicclass XPathReadXml {
private String xmlfile1 = "WebRoot/product2.xml";
private String
public Document getDocument(String xmlfile) throws DocumentException{
SAXReader reader = new SAXReader();
return reader.read(xmlfile);
}
//讀取<product>下<price>的Text值
@Test
publicvoid readText() throws DocumentException{
Document document = getDocument(xmlfile1
//如果路徑以斜線 / 開始, 那麼該路徑就表示到一個元素的絕對路徑
String xmlPath1 = "/catalog/product/price";
//如果路徑以雙斜線 // 開頭, 則表示選擇文件中所有滿足雙斜線//之後規則的元素(無論層級關係)
String xmlPath2 = "//price";
List<Element> priceList = document.selectNodes(xmlPath1);
for (Element price : priceList) {
System.out.println("<"+price.getName()+
}
System.out.println("-------------------");
Element product1 = document.getRootElement().element("product");
//product1的效果和document查詢的效果是一樣的
priceList = product1.selectNodes(xmlPath1);
for (Element price : priceList) {
System.out.println("<"+price.getName()+">"+price.getText()+"</"+price.getName()+">");
}
System.out.println("-------------------");
Element price1 = (Element) document.selectSingleNode(xmlPath1);
if(price1!=null)
System.out.println("<"+price1.getName()+">"+price1.getText()+"</"+price1.getName()+">");
System.out.println("-------------------");
price1 = (Element) document.selectSingleNode(xmlPath2);
System.out.println("<"+price1.getName()+">"+price1.getText()+"</"+price1.getName()+">");
System.out.println("-------------------");
priceList = document.selectNodes(xmlPath2);
for (Element price : priceList) {
System.out.println("<"+price.getName()+">"+price.getText()+"</"+price.getName()+">");
}
/**
* 輸出結果:
<price>80.0</price>
<price>100.0</price>
-------------------
<price>80.0</price>
<price>100.0</price>
-------------------
<price>80.0</price>
-------------------
<price>80.0</price>
-------------------
<price>80.0</price>
<price>100.0</price>
**/
}
//驗證使用者登陸是否成功
@Test
publicvoid valideLogin() throws DocumentException{
Document document = getDocument(xmlfile2);
String username = "aaa";
String password = "aaapass";
String xmlpath = "//user[@name='"+username+"' and @password='"+password+"']";
Node node = document.selectSingleNode(xmlpath);
if (node!=null) {
System.out.println("登陸成功!");
}else {
System.out.println("使用者名稱和密碼不存在!");
}
}
}