java中xpath_java-xpath学习
/**
使用xpath技術取得xml文件中任意級別下的內容 基于dom4j的xpath技術
1)能夠在xml文件中,快速定位需要元素,無需從根元素一個一個的導航到需要的子元素
Document.selectNodes():取得所有符合xpath格式的元素
Document.selectSingleNode():取得所有符合xpath格式的元素的第一個元素
Node類型是Element/Text/Attribute/Document/...類型的父接口
*/
import java.io.File;
import java.util.List;
import java.util.Scanner;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXContentHandler;
import org.dom4j.io.SAXReader;
import org.junit.Test;
/**
* 使用xpath技術取得xml文件中任意級別下的內容 基于dom4j的xpath技術
* 1)能夠在xml文件中,快速定位需要元素,無需從根元素一個一個的導航到需要的子元素
* Document.selectNodes():取得所有符合xpath格式的元素
* Document.selectSingleNode():取得所有符合xpath格式的元素的第一個元素
* Node類型是Element/Text/Attribute/Document/...類型的父接口
* */
public class Xpath {
@Test
public void xpathtest() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/day2/domx/car.xml"));
String xpath = "//單價";
List elementList = document.selectNodes(xpath);
for (Element e : elementList) {
System.out.println(e.getText());
System.out.println("=================");
}
}
@Test
public void xpathtest1() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/day2/domx/car.xml"));
String xpath = "//單價";
List elementList = document.selectNodes(xpath);
System.out.println("第二輛汽車的單價是:" + elementList.get(1).getText());
}
@Test
public void xpathtest2() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/day2/domx/car.xml"));
String xpath = "//單價";
Element element = (Element) document.selectSingleNode(xpath);
System.out.println("第一輛汽車的單價是:" + element.getText());
}
@Test
public void login() throws Exception {
// 讀取用戶在鍵盤的輸入信息
Scanner scanner = new Scanner(System.in);
System.out.println("用戶名:");
String username = scanner.nextLine();
System.out.print("密碼:");
String password = scanner.nextLine();
// System.out.println(username+":"+password);
//解析XML文件,并查詢指定的元素
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("src/day2/domx/users.xml"));
String xpath = "//user[@username='"+username+"' and @password='"+password+"']" ;
Element element = (Element) document.selectSingleNode(xpath);
if(element != null)
{
System.out.println("登陸成功");
}else
{
System.out.println("登陸失敗");
}
}
}
user.xml
結果:
用戶名:
liwen
密碼:123456
登陸成功
總結
以上是生活随笔為你收集整理的java中xpath_java-xpath学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win7 java闪退_win7 sdk
- 下一篇: java arraylist 源代码_J