`

使用xpath获取xml指定节点或节点集工具类

    博客分类:
  • java
阅读更多

使用xpath获取xml指定节点的属性

 

 

1. XmlXPathUtil.java

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * 
 * 
 * <DL>
 * <DT><B> 使用路径表达式(XPath)来获取XML文档中的节点或节点集工具类 </B></DT>
 * <p>
 * <DD>详细介绍</DD>
 * </DL>
 * <p>
 * 
 * <DL>
 * <DT><B>使用范例</B></DT>
 * <p>
 * <DD>使用范例说明</DD>
 * </DL>
 * <p>
 * 
 * @author 周典
 * @version
 */

public class XmlXPathUtil {

	private static final Log logger = LogFactory.getLog(XmlXPathUtil.class);

	/** XML编码 */
	private String encoding = "utf-8";

	private NamespaceContext defaultNamespaceContext;

	public XmlXPathUtil() {
		defaultNamespaceContext = new NamespaceContext() {
			private Map<String, String> m_prefixMap = null;

			public String getNamespaceURI(String prefix) {
				if (null == prefix) {
					throw new NullPointerException("Null prefix");
				} else {
					if ("xml".equals(prefix)) {
						return XMLConstants.XML_NS_URI;
					}
					if (null != m_prefixMap) {
						for (String key : m_prefixMap.keySet()) {
							if (key.equals(prefix)) {
								return m_prefixMap.get(key);
							}
						}
					}
				}
				return XMLConstants.NULL_NS_URI;
			}

			public String getPrefix(String uri) {
				throw new UnsupportedOperationException();
			}

			public Iterator getPrefixes(String uri) {
				throw new UnsupportedOperationException();
			}
		};
	}

	/**
	 * 
	 * 获取XPath的值
	 * 
	 * @param query
	 * 
	 * @param xmlDocument
	 * 
	 * @param defaultNamespaceContext
	 * 
	 * @return String
	 */
	public String evaluateXPath(String query, Node xmlDocument,
			NamespaceContext defaultNamespaceContext) {
		String result = null;
		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		if (defaultNamespaceContext == null) {
			defaultNamespaceContext = this.defaultNamespaceContext;
		}
		xpath.setNamespaceContext(defaultNamespaceContext);
		XPathExpression expr = null;
		try {
			expr = xpath.compile(query);
		} catch (XPathExpressionException xpee) {
			Throwable x = xpee;
			if (null != xpee.getCause()) {
				x = xpee.getCause();
				if ("javax.xml.transform.TransformerException".equals(x
						.getClass().getName())) {
					if (logger.isDebugEnabled()) {
						logger.debug("xpath表达式错误:所有的命名空间需要转换。");
					}
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug("xpath表达式错误:可能表达式格式有误。");
					}
				}
			}
			return null;
		}
		try {
			result = (String) expr.evaluate(xmlDocument, XPathConstants.STRING);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 加载XML String资源
	 * 
	 * @param xmlString
	 *            xml格式的字符串
	 * @return Node
	 * 
	 */
	public Node loadXMLResource(String xmlString) {
		if (0xFEFF == xmlString.charAt(0)) {
			xmlString = xmlString.substring(1);
		}
		InputSource source = new InputSource(new BufferedReader(
				new StringReader(xmlString)));
		return this.xmlSourceToDocument(source);
	}

	/**
	 * 加载XML byte[]资源
	 * 
	 * @param xmlFile
	 *            xml文件
	 * @return Node
	 * 
	 */
	public Node loadXMLResource(byte xmlByte[]) {
		String xmlString = "";
		try {
			xmlString = new String(xmlByte, encoding);
		} catch (UnsupportedEncodingException e) {
			if (logger.isDebugEnabled()) {
				logger.debug(e.getMessage());
			}
		}
		if (0xFEFF == xmlString.charAt(0)) {
			xmlString = xmlString.substring(1);
		}
		InputSource source = new InputSource(new BufferedReader(
				new StringReader(xmlString)));
		return this.xmlSourceToDocument(source);
	}

	/**
	 * 加载XML File资源
	 * 
	 * @param xmlFile
	 *            xml文件
	 * @return Node
	 * 
	 */
	public Node loadXMLResource(File xmlFile) {
		InputSource source = null;
		try {
			source = new InputSource(new FileInputStream(xmlFile));
		} catch (FileNotFoundException e) {
			if (logger.isDebugEnabled()) {
				logger.debug(e.getMessage());
			}
		}
		return this.xmlSourceToDocument(source);
	}

	/**
	 * 
	 * 把xml source 转换为Document
	 * 
	 * @param source
	 * 
	 * @return
	 * 
	 */
	private Node xmlSourceToDocument(InputSource source) {
		source.setEncoding(encoding);
		Document document = null;
		try {
			document = loadDocument(source);
		} catch (SAXParseException spe) {
			if (null != spe.getSystemId()) {
				if (logger.isDebugEnabled()) {
					logger.debug("xpath解析错误,出错的行数是:" + spe.getLineNumber()
							+ ",uri:" + spe.getSystemId());
					logger.debug(spe.getMessage());
				}
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug(spe.getMessage());
				}
			}
			Exception x = spe;
			if (null != spe.getException()) {
				x = spe.getException();
			}
		} catch (SAXException se) {
			document = null;
			if (logger.isDebugEnabled()) {
				logger.debug("解析XML错误,请确保存在格式正确的XML文档。");
			}
			Exception x = se;
			if (null != se.getException()) {
				x = se.getException();
			}
		} catch (IOException ioe) {
			document = null;
			if (logger.isDebugEnabled()) {
				logger.debug("不能加载文档,文档不可读取。");
			}
		}
		return document;
	}

	/**
	 * 
	 * 从InputSource加载document
	 * 
	 * @param source
	 * @return Node
	 * @throws SAXException
	 * @throws IOException
	 */
	private Document loadDocument(InputSource source) throws SAXException,
			IOException {
		Document document = null;
		DocumentBuilder parser = null;
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		domFactory.setNamespaceAware(true);
		domFactory.setValidating(false);
		try {
			parser = domFactory.newDocumentBuilder();
		} catch (ParserConfigurationException pce) {
			if (logger.isDebugEnabled()) {
				logger.debug(pce.getMessage());
			}
		}
		parser.reset();
		document = parser.parse(source);
		return document;
	}

	/**
	 * 
	 * 设置xml编码
	 * 
	 * @param encoding
	 */
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		xmlString += "<books>";
		xmlString += "<book><name>Action1</name></book>";
		xmlString += "<book><name first='asdf'>Action2</name></book>";
		xmlString += "</books>";
		XmlXPathUtil xmlXPathUtil = new XmlXPathUtil();
		xmlXPathUtil.setEncoding("utf-8");
		Node fileNode = xmlXPathUtil
				.loadXMLResource(new File(
						"F:\\客户信息查询.xml"));
		Node strNode = xmlXPathUtil.loadXMLResource(xmlString);
		String strValue = xmlXPathUtil.evaluateXPath("//book", strNode, null);
		String fileValue = xmlXPathUtil
				.evaluateXPath(
						"/service[ @name='' ]/sys-header/data[ @name='SYS_HEAD' ]/struct/data[ @name='MESSAGE_TYPE' ]/field[1]/text()",
						fileNode, null);
		System.out.println("execute result: " + strValue);
		System.out.println("execute result: " + fileValue);
	}
}


2. 客户信息查询.xml

 

<?xml version="1.0" encoding="GB2312"?>
<service name="">
	<sys-header>
		<data name="SYS_HEAD">
			<struct>
				<data name="MESSAGE_TYPE">
					<field type="string" length="4" encrypt-mode="">1400</field>
					<field type="string" length="4" encrypt-mode="">1401</field>
				</data>
				<data name="MESSAGE_CODE">
					<field type="string" length="6" encrypt-mode="">9100</field>
				</data>
				<data name="SERVICE_CODE">
					<field type="string" length="8" encrypt-mode="">SVR_INQUIRY1</field>
					<field type="string" length="8" encrypt-mode="">SVR_INQUIRY2</field>
				</data>
			</struct>
		</data>
	</sys-header>
	<app-header>
		<data name="APP_HEAD">
			<struct>
				<data name="PGUP_OR_PGDN">
					<field type="string" length="1" encrypt-mode="">1</field>
				</data>
				<data name="TOTAL_NUM">
					<field type="string" length="10" encrypt-mode="">10</field>
				</data>
				<data name="CURRENT_NUM">
					<field type="string" length="10" encrypt-mode="">0</field>
				</data>
				<data name="PAGE_START">
					<field type="string" length="10" encrypt-mode="">0</field>
				</data>
				<data name="PAGE_END">
					<field type="string" length="10" encrypt-mode="">0</field>
				</data>
			</struct>
		</data>
	</app-header>
	<body>
		<data name="CLIENT_NO">
			<field type="string" length="12" encrypt-mode="">1234567890123</field>
		</data>
		<data name="GLOBAL_ID">
			<field type="string" length="25" encrypt-mode="">1234567890123456789012345</field>
		</data>
		<data name="GLOBAL_TYPE">
			<field type="string" length="3" encrypt-mode="">123</field>
		</data>
		<data name="ISS_COUNTRY">
			<field type="string" length="3" encrypt-mode="">123</field>
		</data>
	</body>
</service>

 

 

 

 

 

分享到:
评论

相关推荐

    javascript封装的通用解析和操作xml文件数据工具类(含测试使用代码)

    javascript封装的通用解析和操作xml文件数据工具类(含测试使用代码) javascript封装的通用解析和操作xml文件数据工具类(含测试使用代码) 测试数据: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;root&gt; &lt;book&gt; ...

    XpathDemo.zip

    JsoupXPath的节点对象JXNode不仅可以获取标签节点,还可以获取属性节点 HtmlCleaner是一个开源的Java语言的Html文档解析器。HtmlCleaner能够重新整理HTML文档的每个元素并生成结构良好(Well-Formed)的 HTML 文档。...

    一个Java XML工具类(开源)

    1.强大的查询能力,支持xpath(2...3.轻松添加或插入新节点等 4.删除功能 等等...(具体查阅javadoc,测试的junit文件和xml文件) 该xml工具开源,没有任何license,经过严格junit测试,可以用在日常开发中。 support me!

    Welldom:PHP的XML工具箱

    Welldom,PHP的XML工具箱 ... 要加载该库,请使用任何兼容的类加载器或仅需要src/autoload.php文件。 require __DIR__ . '/path/to/expdom/src/autoload.php' ; 用法 加载XML文档: &lt;?php use Welldom \ Document

    Python利用Xpath选择器爬取京东网商品信息

    XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。 首先进入京东网,输入自己想要查询的商品,向服务器发送网页请求。在这里小编仍以关键词“狗粮”作为搜索对象,之后得到后面...

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part2

    1.5 xml的编辑工具 7 1.6 xml文档 8 1.6.1 xml声明 9 1.6.2 文档类型声明 10 1.6.3 元素 11 1.6.4 注释 15 1.6.5 处理指令 15 1.6.6 空白处理 16 1.6.7 行尾处理 16 1.6.8 语言标识 16 1.7 格式良好的xml ...

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part3

    1.5 xml的编辑工具 7 1.6 xml文档 8 1.6.1 xml声明 9 1.6.2 文档类型声明 10 1.6.3 元素 11 1.6.4 注释 15 1.6.5 处理指令 15 1.6.6 空白处理 16 1.6.7 行尾处理 16 1.6.8 语言标识 16 1.7 格式良好的xml ...

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part4

    1.5 xml的编辑工具 7 1.6 xml文档 8 1.6.1 xml声明 9 1.6.2 文档类型声明 10 1.6.3 元素 11 1.6.4 注释 15 1.6.5 处理指令 15 1.6.6 空白处理 16 1.6.7 行尾处理 16 1.6.8 语言标识 16 1.7 格式良好的xml ...

    JAVA WEB 开发详解:XML+XSLT+SERVLET+JSP 深入剖析与实例应用.part5

    1.5 xml的编辑工具 7 1.6 xml文档 8 1.6.1 xml声明 9 1.6.2 文档类型声明 10 1.6.3 元素 11 1.6.4 注释 15 1.6.5 处理指令 15 1.6.6 空白处理 16 1.6.7 行尾处理 16 1.6.8 语言标识 16 1.7 格式良好的xml ...

    ASP.NET4高级程序设计第4版 带目录PDF 分卷压缩包 part1

    14.5.2 使用XPath搜索XmlDocument 14.5.3 使用LINQ搜索XDocument 14.6 验证XML内容 14.6.1 基本架构 14.6.2 验证XmlDocument 14.6.3 使用XDocument进行验证 14.7 转换XML内容 14.7.1 基本的样式表 ...

    XQuery权威指南(简码·扫描版)

     本书比较深入全面地介绍了XQuery相关知识,包括XQuery的概述和快速指南,如何使用XQuery编写简单和复杂的查询,如何对XML数据过滤、排序和分组,还讲述了FLWOR表达式、XPath及提取、组合数据的XQuery工具。...

    ASP.NET4高级程序设计(第4版) 3/3

    14.5.2 使用XPath搜索XmlDocument 493 14.5.3 使用LINQ搜索XDocument 494 14.6 验证XML内容 496 14.6.1 基本架构 496 14.6.2 验证XmlDocument 497 14.6.3 使用XDocument进行验证 498 14.7 转换XML内容...

    2.ASP.NET.2.0.高级编程(第4版) [1/7]

    13.3.2 XPath、XPathDocument和XmlDocument 438 13.4 DataSet 442 13.4.1 把DataSet保存到XML中 442 13.4.2 XmlDataDocument 443 13.5 XmlDataSource控件 445 13.6 XSLT 449 13.6.1 XslCompiledTransform 450 ...

    ASP.NET2.0高级编程(第4版)1/6

    26.3 使用简单的XML Web服务953 26.3.1 添加Web引用953 26.3.2 在客户应用程序中  调用Web服务955 26.4 Web服务的传输协议957 26.4.1 HTTP-GET959 26.4.2 HTTP-POST961 26.4.3 SOAP962 26.5 WebMethod的重载962 ...

    asp.net知识库

    常用编码工具类,支持base64,md5,des,crc32 也谈谈技术面试 在C#里把ArrayList转换为Array 或 把Array转换为ArrayList C# 2.0 在.NET 2.0中,让你的组件也可以绑定 .NET20 一种简单的窗口控件UI状态控制方法 翻译MSDN...

    Java学习笔记-个人整理的

    {4.8}Collections集合工具类}{86}{section.4.8} {4.9}Comparable与Comparator}{86}{section.4.9} {4.9.1}Comparable}{86}{subsection.4.9.1} {4.9.2}Comparator}{87}{subsection.4.9.2} {4.10}包装类}{87}{...

Global site tag (gtag.js) - Google Analytics