XPath是获取xml中数据的一种方式,其简单语法结构如下(引用自w3c):
XPath 使用路径表达式来选取 XML 文档中的节点或节点集。节点是通过沿着路径 (path) 或者步 (steps) 来选取的。
XML 实例文档
我们将在下面的例子中使用这个 XML 文档。
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
选取节点
XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。
下面列出了最有用的路径表达式:
表达式 | 描述 |
nodename | 选取此节点的所有子节点。 |
/ | 从根节点选取。 |
// | 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。 |
. | 选取当前节点。 |
.. | 选取当前节点的父节点。 |
@ | 选取属性。 |
实例
在下面的表格中,我们已列出了一些路径表达式以及表达式的结果:
路径表达式 | 结果 |
bookstore | 选取 bookstore 元素的所有子节点。 |
/bookstore | 选取根元素 bookstore。 注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径! |
bookstore/book | 选取属于 bookstore 的子元素的所有 book 元素。 |
//book | 选取所有 book 子元素,而不管它们在文档中的位置。 |
bookstore//book | 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。 |
//@lang | 选取名为 lang 的所有属性。 |
谓语(Predicates)
谓语用来查找某个特定的节点或者包含某个指定的值的节点。
谓语被嵌在方括号中。
实例
在下面的表格中,我们列出了带有谓语的一些路径表达式,以及表达式的结果:
路径表达式 | 结果 |
/bookstore/book[1] | 选取属于 bookstore 子元素的第一个 book 元素。 |
/bookstore/book[last()] | 选取属于 bookstore 子元素的最后一个 book 元素。 |
/bookstore/book[last()-1] | 选取属于 bookstore 子元素的倒数第二个 book 元素。 |
/bookstore/book[position()<3] | 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。 |
//title[@lang] | 选取所有拥有名为 lang 的属性的 title 元素。 |
//title[@lang='eng'] | 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。 |
/bookstore/book[price>35.00] | 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。 |
/bookstore/book[price>35.00]/title | 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。 |
选取未知节点
XPath 通配符可用来选取未知的 XML 元素。
通配符 | 描述 |
* | 匹配任何元素节点。 |
@* | 匹配任何属性节点。 |
node() | 匹配任何类型的节点。 |
实例
在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:
路径表达式 | 结果 |
/bookstore/* | 选取 bookstore 元素的所有子元素。 |
//* | 选取文档中的所有元素。 |
//title[@*] | 选取所有带有属性的 title 元素。 |
选取若干路径
通过在路径表达式中使用“|”运算符,您可以选取若干个路径。
实例
在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:
路径表达式 | 结果 |
//book/title | //book/price | 选取 book 元素的所有 title 和 price 元素。 |
//title | //price | 选取文档中的所有 title 和 price 元素。 |
/bookstore/book/title | //price | 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素。 |
以上为xpath的基本语法,在Java中xpath的使用也很简单,为使用方便,对xpath的操作做了如下封装:
/*
* Title:XMLUtil.java<br>
* Date: 2016年1月28日 下午5:32:13<br>
*
*/
package com.testXpath.util;
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* <br>
* xpath辅助类
* @version 1.0
*/
public class XMLUtil
{
javax.xml.xpath.XPath oXpath;
/**
* 构造xml文档对应的document对象
* @param file
* @return
* @throws Exception
*/
public Document parseFile(File file) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.parse(file);
// 创建XPath对象
XPathFactory factory = XPathFactory.newInstance();
oXpath = factory.newXPath();
return doc;
}
/**
* 构造输入流对应的document对象
* @param in
* @return
* @throws Exception
*/
public Document parseStream(InputStream in) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.parse(in);
// 创建XPath对象
XPathFactory factory = XPathFactory.newInstance();
oXpath = factory.newXPath();
return doc;
}
/**
* 获取结点值
* @param node
* @return
*/
public String getNodeValue(Node node)
{
String dataValue = node.getTextContent();
return dataValue;
}
/**
* 获取结点List
* @param node
* @param xpath
* @return
* @throws XPathExpressionException
*/
public NodeList getNodeList(org.w3c.dom.Node node, String xpath) throws XPathExpressionException
{
NodeList nodeList = (NodeList) oXpath.evaluate(xpath, node, XPathConstants.NODESET);
return nodeList;
}
/**
* 获取单个结点
* @param node
* @param xpath
* @return
* @throws XPathExpressionException
*/
public Node getNode(org.w3c.dom.Node node, String xpath) throws XPathExpressionException
{
Node nodeRet = (Node) oXpath.evaluate(xpath, node, XPathConstants.NODE);
return nodeRet;
}
}
基于封装的辅助类XMLUtil,读取连接池配置文件中的参数值,测试代码如下:
/*
* Title:XpathTest.java<br>
* Date: 2017年1月4日 下午3:38:55<br>
*
*/
package com.testXpath.boot;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Connection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.testXpath.util.XMLUtil;
/**
* <br>
*
* @version 1.0
*/
public class XpathTest
{
private static void getConfigParams() throws Exception
{
String configPath = getConfigPath() + "DBConfig.xml";
XMLUtil xmlUtil = new XMLUtil();
Document doc = xmlUtil.parseFile(new File(configPath));
Node typeNode = xmlUtil.getNode(doc, "//type");
String type = xmlUtil.getNodeValue(typeNode);
Node driverClassNode = xmlUtil.getNode(doc, "//driver");
String driverClass = xmlUtil.getNodeValue(driverClassNode);
Node urlNode = xmlUtil.getNode(doc, "//url");
String url = xmlUtil.getNodeValue(urlNode);
Node userNameNode = xmlUtil.getNode(doc, "//username");
String userName = xmlUtil.getNodeValue(userNameNode);
Node passwordNode = xmlUtil.getNode(doc, "//password");
String password = xmlUtil.getNodeValue(passwordNode);
Node initialPoolSizeNode = xmlUtil.getNode(doc, "//initialPoolSize");
String initialPoolSize = xmlUtil.getNodeValue(initialPoolSizeNode);
Node maxPoolSizeNode = xmlUtil.getNode(doc, "//maxPoolSize");
String maxPoolSize = xmlUtil.getNodeValue(maxPoolSizeNode);
Node minPoolSizeNode = xmlUtil.getNode(doc, "//minPoolSize");
String minPoolSize = xmlUtil.getNodeValue(minPoolSizeNode);
System.out.println("连接池配置参数如下:\n" + "type:" + type + "\n驱动类:" + driverClass + "\n连接url:" + url + "\n用户名:"
+ userName + "\n密码" + password + "\n连接池初始连接数:" + initialPoolSize + "\n最大连接数:" + maxPoolSize + "\n最小连接数:"
+ minPoolSize);
}
/**
*
* Description:配置文件所在路径的构造,如果运行时客户有设置,则找客户定义的路径,否则默认使用/conf下的配置文件<br>
*
* @param path
*/
private static String getConfigPath()
{
return new StringBuffer().append(getProjectPath()).append(File.separator).toString();
}
/**
* 得到项目根路径
*
* @return
*/
private static String getProjectPath()
{
// Startup.class所在路径
URL url = XpathTest.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try
{
filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
if (filePath.endsWith(".jar"))
{
// 过滤掉路径中的jar包名
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
File f = null;
if ("lib/".equals(filePath.substring(filePath.length() - 4, filePath.length())))
{
// filePath = filePath + "../";
filePath = filePath.substring(0, filePath.length() - 4);
}
f = new File(filePath);
filePath = f.getAbsolutePath();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
System.exit(0);
}
return filePath;
}
public static void main(String[] args) throws Exception
{
getConfigParams();
}
}