首先导包:
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
代码
public class XPATHTest {
public static void main(String[] args) throws Exception {
base();
}
public static void base() throws Exception {
Document doc = new SAXReader().read(new File("./src/test/stu.xml"));
String xpath = "";
/**
* / 绝对路径 表示从xml的根位置开始或子元素(一个层次机构)
* // 相对路径 表示不分任何层次结构的选择元素
* * 通配符 表示匹配所有元素
* [] 条件 表示选择什么条件下的元素
* @ 属性 表示选择属性节点
* text() 表示选择文本内容
*
* Element ele = (Element) doc.selectSingleNode(xpath);//得到一个
System.out.println(ele.getName());
*/
xpath = "/Students";//得到Students标签
xpath = "/Student/student";//得到Students标签下的student标签
xpath = "//student"; //得到xml中的所有student标签
List<Element> ele = doc.selectNodes(xpath);//得到所有
// // System.out.println(ele.getName());
// for(Element e : ele){
// System.out.println(e.getName());
// }
xpath = "/student/*";//得到student标签下的所有子标签
xpath = "/student//*";//得到student标签下的所有标签(不分层次)
xpath = "//student[2]";//得到第二个student标签
xpath = "//student[last()]";//得到最后一个student标签
xpath = "//@id";//选择id属性节点对象,返回Attribute对象
xpath = "//student[@id]";//得到带有id属性的标签
xpath = "//student[@id='2']";//得到id属性值为2的标签
xpath = "//name/text()"; //选择name标签下的文本内容,返回Text对象
xpath = "//name[text()=='张三']";//得到name标签的文本内容为张三的name标签
}
public static void test1() throws Exception {
Document doc = new SAXReader().read(new File("./src/test/stu.xml"));
//使用XPATH技术查询id=2的学生标签
Element ele = (Element) doc.selectSingleNode("//student[@id='2']");
ele.detach();//删除标签
FileOutputStream out = new FileOutputStream("D:/stu.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.close();
}
}