---
title: "利用xpath获取节点值实例"
author: "yonge812"
date: "2013-08-27T12:01:52Z"
tags: ["DOM", "XML", "XML解析", "document", "xpath"]
categories: ["行业应用"]
slug: "xpath"
draft: false
lastmod: "2013-08-27T12:01:52Z"
id: 1931501
url: "https://yonge812.iteye.com/blog/1931501"
---

这几天做xml打包、解包的通用工具，学习了下xpath的使用方法，它可以很方便查询某一节点的值，有点类似于jquery的选择器，具体事例如下：

```
public String queryNodeValue(final Document doc, String expression)
			throws XPathExpressionException {
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();

		xpath.setNamespaceContext(new NamespaceContext() {

			@SuppressWarnings("rawtypes")
			@Override
			public Iterator getPrefixes(String namespaceURI) {
				throw new UnsupportedOperationException();
			}

			@Override
			public String getPrefix(String namespaceURI) {
				throw new UnsupportedOperationException();
			}

			@Override
			public String getNamespaceURI(String prefix) {
				return doc.lookupNamespaceURI(prefix);
			}
		});
		XPathExpression expr = xpath.compile(expression);

		Object result = expr.evaluate(doc, XPathConstants.STRING);
		return result == null ? null : result.toString();
	}
```

  上面是获取document的元素值的通用方法。