有中文文档:
有22个案例可帮你快速入门:
>> 实例 1 <<
基本的XPath语法类似于在一个文件系统中定位文件,如果路径以斜线 / 开始, 那么该路径就表示到一个元素的绝对路径
/AAA |
---|
选择根元素AAA |
<AAA> <BBB/> <CCC/> <BBB/> <BBB/> <DDD> <BBB/> </DDD> <CCC/> </AAA> |
/AAA/CCC |
---|
选择AAA的所有CCC子元素 |
<AAA> <BBB/> <CCC/> <BBB/> <BBB/> <DDD> <BBB/> </DDD> <CCC/> </AAA> |
/AAA/DDD/BBB |
---|
选择AAA的子元素DDD的所有子元素 |
<AAA> <BBB/> <CCC/> <BBB/> <BBB/> <DDD> <BBB/> </DDD> <CCC/> </AAA> |
>> 实例 2 <<
如果路径以双斜线 // 开头, 则表示选择文档中所有满足双斜线//之后规则的元素(无论层级关系)
//BBB |
---|
选择所有BBB元素 |
<AAA> <BBB/> <CCC/> <BBB/> <DDD> <BBB/> </DDD> <CCC> <DDD> <BBB/> <BBB/> </DDD> </CCC> </AAA> |
//DDD/BBB |
---|
选择所有父元素是DDD的BBB元素 |
<AAA> <BBB/> <CCC/> <BBB/> <DDD> <BBB/> </DDD> <CCC> <DDD> <BBB/> <BBB/> </DDD> </CCC> </AAA> |
>> 实例 3 <<
星号 * 表示选择所有由星号之前的路径所定位的元素
/AAA/CCC/DDD/* |
---|
选择所有路径依附于/AAA/CCC/DDD的元素 |
<AAA> <XXX> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </XXX> <CCC> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </CCC> <CCC> <BBB> <BBB> <BBB/> </BBB> </BBB> </CCC> </AAA> |
/*/*/*/BBB |
---|
选择所有的有3个祖先元素的BBB元素 |
<AAA> <XXX> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </XXX> <CCC> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </CCC> <CCC> <BBB> <BBB> <BBB/> </BBB> </BBB> </CCC> </AAA> |
//* |
---|
选择所有元素 |
<AAA> <XXX> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </XXX> <CCC> <DDD> <BBB/> <BBB/> <EEE/> <FFF/> </DDD> </CCC> <CCC> <BBB> <BBB> <BBB/> </BBB> </BBB> </CCC> </AAA> |
>> 实例 4 <<
方块号里的表达式可以进一步的指定元素, 其中数字表示元素在选择集里的位置, 而last()函数则表示选择集中的最后一个元素.
/AAA/BBB[1] |
---|
选择AAA的第一个BBB子元素 |
<AAA> <BBB/> <BBB/> <BBB/> <BBB/> </AAA> |
/AAA/BBB[last()] |
---|
选择AAA的最后一个BBB子元素 |
<AAA> <BBB/> <BBB/> <BBB/> <BBB/> </AAA> |
>> 实例 5 <<
//@id |
---|
选择所有的id属性 |
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA> |
//BBB[@id] |
---|
选择有id属性的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA> |
//BBB[@name] |
---|
选择有name属性的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA> |
//BBB[@*] |
---|
选择有任意属性的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA> |
//BBB[not(@*)] |
---|
选择没有属性的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA> |
>> 实例 6 <<
属性的值可以被用来作为选择的准则, normalize-space函数删除了前部和尾部的空格, 并且把连续的空格串替换为一个单一的空格
//BBB[@id='b1'] |
---|
选择含有属性id且其值为'b1'的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB name = " bbb "/> <BBB name = "bbb"/> </AAA> |
//BBB[@name='bbb'] |
---|
选择含有属性name且其值为'bbb'的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB name = " bbb "/> <BBB name = "bbb"/> </AAA> |
//BBB[normalize-space(@name)='bbb'] |
---|
选择含有属性name且其值(在用normalize-space函数去掉前后空格后)为'bbb'的BBB元素 |
<AAA> <BBB id = "b1"/> <BBB name = " bbb "/> <BBB name = "bbb"/> </AAA> |
>> 实例 7 <<
count()函数可以计数所选元素的个数
//*[count(BBB)=2] |
---|
选择含有2个BBB子元素的元素 |
<AAA> <CCC> <BBB/> <BBB/> <BBB/> </CCC> <DDD> <BBB/> <BBB/> </DDD> <EEE> <CCC/> <DDD/> </EEE> </AAA> |
//*[count(*)=2] |
---|
选择含有2个子元素的元素 |
<AAA> <CCC> <BBB/> <BBB/> <BBB/> </CCC> <DDD> <BBB/> <BBB/> </DDD> <EEE> <CCC/> <DDD/> </EEE> </AAA> |
//*[count(*)=3] |
---|
选择含有3个子元素的元素 |
<AAA> <CCC> <BBB/> <BBB/> <BBB/> </CCC> <DDD> <BBB/> <BBB/> </DDD> <EEE> <CCC/> <DDD/> </EEE> </AAA> |
后面的不常用,就不一一列举,需要时可自行查文档。
dom4j 中引用 Xpath:
Powerful Navigation with XPath
In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.
public void bar(Document document) { List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" ); }
For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.
public void findLinks(Document document) throws DocumentException { List list = document.selectNodes( "//a/@href" ); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); } }
API:
org.dom4j
Interface Document
Methods inherited from interface org.dom4j.Node |
accept, asXML, asXPathResult, clone, createXPath, detach, getDocument, getName, getNodeType, getNodeTypeName, getParent, getPath, getPath, getStringValue, getText, getUniquePath, getUniquePath, hasContent, isReadOnly, matches, numberValueOf, selectNodes, selectNodes, selectNodes, selectObject, selectSingleNode, setDocument, setName, setParent, setText, supportsParent, valueOf, write |
List | selectNodes(String xpathExpression) selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression. |
List | selectNodes(String xpathExpression, String comparisonXPathExpression) selectNodes evaluates an XPath expression then sorts the results using a secondary XPath expression Returns a sorted List of Node instances. |
List | selectNodes(String xpathExpression, String comparisonXPathExpression, boolean removeDuplicates) selectNodes evaluates an XPath expression then sorts the results using a secondary XPath expression Returns a sorted List of Node instances. |
Node | selectSingleNode(String xpathExpression) selectSingleNode evaluates an XPath expression and returns the result as a single Node instance. |
利用xpath和dom4j的结合,获取XML文档的某个节点:
出现错误,导入jaxen的jar包:
编码:
book.xml :
<?xml version="1.0" encoding="UTF-8"?>
<书架>
<书 name="yyyyy">
<售价>109元</售价>
<售价>19元</售价>
<售价>19元</售价>
<售价>209元</售价>
<书名>Java就业培训教程</书名>
<作者>张孝祥</作者>
<售价>19元</售价>
<售价>19元</售价>
<售价>19元</售价>
</书>
<书>
<书名>JavaScript网页开发</书名>
<作者>张孝祥</作者>
<售价>28.00元</售价>
</书>
</书架>
package cn.itcast.dom4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class Demo1 {
//获取:<书名>JavaScript网页开发</书名>
@Test
public void findWithXPath() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element ele = (Element)document.selectNodes("//书名").get(1);
System.out.println(ele.getText());
}
}
模拟用户管理系统:
新建一个users.xml,存放用户数据:
编码:
users.xml :
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user username="aaa" password="123" />
<user username="bbb" password="123" />
<user username="ccc" password="123" />
</users>
package cn.itcast.dom4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class Demo1 {
//模拟用户管理系统:判断用户名和密码是否正确。
@Test
public void findUser() throws Exception{
String username = "bbb";
String password = "123";
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/users.xml"));
Element user = (Element)document.selectSingleNode("//user[@username='"+username+"' and @password='"+password+"']");
if(user!=null){
System.out.println("让用户登录成功!");
}else{
System.out.println("用户名或密码错误!");
}
}
}
字符串与XML的转换
1.将字符串转化为XML
String text = "<members> <member>sitinspring</member></members>";Document document = DocumentHelper.parseText(text);
2.将文档或节点的XML转化为字符串.
SAXReader reader = new SAXReader();Document document = reader.read(new File("input.xml"));
Element root=document.getRootElement();
String docXmlText=document.asXML();
String rootXmlText=root.asXML();
Element memberElm=root.element("member");
String memberXmlText=memberElm.asXML();
package cn.itcast.dom4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class Demo1 {
//将字符串转化为XML
@Test
public void string2xml() throws Exception{
String text = "<members> <member>lalala</member> </members>";
Document member = DocumentHelper.parseText(text);
OutputFormat format = OutputFormat.createPrettyPrint(); //漂亮格式
//format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/member.xml"),format); //这里一般不要用字符流,因为字符流有时默认是GB2312,它的构造方法又不能指定码表.而XML文档一般都是UTF-8编码的,避免出现XML文档乱码。
writer.write(member);
writer.close();
}
//将文档或节点的XML转化为字符串
@Test
public void xml2string() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/member.xml"));
Element root = document.getRootElement();
String doc = document.asXML();
String roo = root.asXML();
//System.out.println(doc);
//System.out.println(roo);
Element ele = root.element("member");
String eleText = ele.asXML();
System.out.println(eleText);
}
}