`
yunzhu
  • 浏览: 1144331 次
  • 性别: Icon_minigender_1
  • 来自: 南京
博客专栏
B2b19957-cda7-3a9e-83a0-418743feb0ca
监控应用服务器
浏览量:109696
2e8be8be-e51f-346c-bcdd-12623c9aa820
Web前端开发
浏览量:119659
Bfa5df64-a623-34b9-85b8-ef3ce2aed758
经典异常的解决
浏览量:204460
社区版块
存档分类
最新评论

使用XPath解析XML的工具类

阅读更多

目录结构一览

一、首先看一下XPath的简单介绍


二、使用XPath的解析XML的工具类

 

三、通过一个测试类展示工具类的使用

     ---只是用于测试,此种写法不适用于实际项目中

 

四、上面的测试类所使用的XML文件

 

五、适用于项目中的写法(XML Node→Object)

      ---解析一个XML节点,直接转换为一个对象并返回给调用者

      1、解析XML返回对象的封装类

      2、上面类的单元测试类

      3、使用到的Bean类

 

 

首先看一下XPath的简单介绍

什么是XPath?

  • XPath使用路径表达式在XML文档中进行导航
  • XPath包含一个标准函数库
  • XPath是 XSLT 中的主要元素
  • XPath是一个 W3C 标准

XPath路径表达式
XPath使用路径表达式来选取XML文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。

 

XPath标准函数
XPath含有超过100个内建的函数。这些函数用于字符串值、数值、日期和时间比较、节点和QName处理、序列处理、逻辑值等等。

 

在XPath中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档节点(或称为根节点)。

 

XPath使用路径表达式来选取XML文档中的节点或节点集。节点是通过沿着路径(path)或者步(steps)来选取的。

 

 

使用XPath的解析XML的工具类

好吧,这还是09年底写的,会不会太老旧了?

 

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 解析XML的工具类,使用XPath
 * 
 * @author ChenFeng
 * @version [版本号, 2009-12-22]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class XMLParseUtil {
	private DocumentBuilder builder;

	private XPath xpath;

	/**
	 * 默认构造函数
	 * 
	 * @throws ParserConfigurationException
	 *             创建XML解析器出错!
	 */
	public XMLParseUtil() throws ParserConfigurationException {
		DocumentBuilderFactory domfactory = DocumentBuilderFactory
				.newInstance();
		builder = domfactory.newDocumentBuilder();

		XPathFactory xpfactory = XPathFactory.newInstance();
		xpath = xpfactory.newXPath();
	}

	/**
	 * 根据路径解析XML文档
	 * 
	 * <pre>
	 * 可能产生而没有显式抛出的异常:
	 * 1) MalformedURLException :传入文件路径错误!找不到要解析的文件!
	 * 2) SAXParseException : 文件格式错误!无法解析!
	 * </pre>
	 * 
	 * @param path
	 *            文件路径
	 * @return Document对象
	 * @throws IOException
	 *             IO异常
	 * @throws SAXException
	 *             SAX异常
	 * @see [类、类#方法、类#成员]
	 */
	public Document parseDocument(String path) throws IOException, SAXException {
		return builder.parse(path);
	}

	/**
	 * 根据文件解析XML文档
	 * 
	 * <pre>
	 * 可能产生而没有显式抛出的异常:
	 * 1) IllegalArgumentException :传入参数错误!如对象不能为空!
	 * 2) SAXParseException : 文件格式错误!无法解析!
	 * </pre>
	 * 
	 * @param file
	 *            文件
	 * @return Document对象
	 * @throws IOException
	 *             IO异常
	 * @throws SAXException
	 *             SAX异常
	 * @see [类、类#方法、类#成员]
	 */
	public Document parseDocument(File file) throws IOException, SAXException {
		return builder.parse(file);
	}

	/**
	 * 根据输入流解析XML文档
	 * 
	 * <pre>
	 * 可能产生而没有显式抛出的异常:
	 * 1) IllegalArgumentException :传入参数错误!如对象不能为空!
	 * 2) SAXParseException : 文件格式错误!无法解析!
	 * </pre>
	 * 
	 * @param is
	 *            输入流
	 * @return Document对象
	 * @throws IOException
	 *             IO异常
	 * @throws SAXException
	 *             SAX异常
	 * @see [类、类#方法、类#成员]
	 */
	public Document parseDocument(InputStream is) throws IOException,
			SAXException {
		return builder.parse(is);
	}

	/**
	 * 通过xpath取得节点列表
	 * 
	 * @param node
	 *            节点
	 * @param expression
	 *            XPath表达式
	 * @return NodeList
	 * @throws XPathExpressionException
	 *             XPath表达式异常
	 * @see [类、类#方法、类#成员]
	 */
	public NodeList selectNodes(Node node, String expression)
			throws XPathExpressionException {
		// XPath对象编译XPath表达式
		XPathExpression xpexpreesion = this.xpath.compile(expression);
		Object object = xpexpreesion.evaluate(node, XPathConstants.NODESET);
		return (NodeList) object;
	}

	/**
	 * 通过xpath取得单个节点
	 * 
	 * @param node
	 *            节点
	 * @param expression
	 *            XPath表达式
	 * @return Node
	 * @throws XPathExpressionException
	 *             XPath表达式异常
	 * @see [类、类#方法、类#成员]
	 */
	public Node selectSingleNode(Node node, String expression)
			throws XPathExpressionException {
		XPathExpression xpexpreesion = this.xpath.compile(expression);
		Object object = xpexpreesion.evaluate(node, XPathConstants.NODE);
		return (Node) object;
	}

	/**
	 * 根据xpath取得节点的文本值
	 * 
	 * @param node
	 *            节点
	 * @param expression
	 *            XPath表达式
	 * @return String
	 * @throws XPathExpressionException
	 *             XPath表达式异常
	 * @see [类、类#方法、类#成员]
	 */
	public String getNodeStringValue(Node node, String expression)
			throws XPathExpressionException {
		XPathExpression xpexpreesion = this.xpath.compile(expression);
		Object object = xpexpreesion.evaluate(node, XPathConstants.STRING);
		return (String) object;
	}
}

 

通过一个测试类展示工具类的使用

只是用于测试,此种写法不适用于实际项目中

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * 入口程序
 * 
 * @author ChenFeng
 * @version [版本号, 2009-12-21]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class XMLParseUtilTest {

	/**
	 * 入口函数
	 * 
	 * @param args
	 * @see [类、类#方法、类#成员]
	 */
	public static void main(String[] args) {
		String path = XMLParseUtilTest.class.getResource("bookstore.xml")
				.getPath();

		XMLParseUtil xmlParse = null;
		try {
			xmlParse = new XMLParseUtil();
		} catch (ParserConfigurationException e) {
			System.out.println("异常:创建XML解析器过程中有一个严重的配置错误!");
			e.printStackTrace();
		}
		if (null != xmlParse) {
			Document doc = null;
			try {
				doc = xmlParse.parseDocument(path);
			} catch (MalformedURLException e) {
				System.out.println("异常:传入文件路径错误!找不到要解析的文件!");
				e.printStackTrace();
			} catch (SAXParseException e) {
				System.out.println("异常:文件格式错误!无法解析!");
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}

			if (null != doc) {
				NodeList bookNodeList = null;
				try {
					/**
					 * [title/@lang='en']表示选取的book节点,必须满足子节点title的lang属性为en
					 */
					bookNodeList = (NodeList) xmlParse.selectNodes(doc,
							"//bookstore/book[title/@lang='en']");
				} catch (XPathExpressionException e) {
					System.out.println("异常:XPath表达式错误!");
					e.printStackTrace();
				}

				if (null != bookNodeList) {
					List<Book> bookList = new ArrayList<Book>();

					for (int i = 0; i < bookNodeList.getLength(); i++) {
						Node node = bookNodeList.item(i);
						Book book = parseBookNode(xmlParse, node);
						bookList.add(book);
					}

					for (Book book : bookList) {
						System.out.println(book.toString());
					}
				}
			}
		}
	}

	/**
	 * 解析单个book节点
	 * 
	 * @param util
	 * @param node
	 * @return
	 * @throws XPathExpressionException
	 * @see [类、类#方法、类#成员]
	 */
	public static Book parseBookNode(XMLParseUtil util, Node node) {
		String lang = "";
		String title = "";
		String author = "";
		String year = "";
		String price = "";

		try {
			title = util.getNodeStringValue(node, "./title");
		} catch (XPathExpressionException e) {
			System.out.println("异常:XPath表达式错误!");
			e.printStackTrace();
		}
		try {
			lang = util.getNodeStringValue(node, "./title/@lang");
		} catch (XPathExpressionException e) {
			System.out.println("异常:XPath表达式错误!");
			e.printStackTrace();
		}
		try {
			author = util.getNodeStringValue(node, "./author");
		} catch (XPathExpressionException e) {
			System.out.println("异常:XPath表达式错误!");
			e.printStackTrace();
		}
		try {
			year = util.getNodeStringValue(node, "./year");
		} catch (XPathExpressionException e) {
			System.out.println("异常:XPath表达式错误!");
			e.printStackTrace();
		}
		try {
			price = util.getNodeStringValue(node, "./price");
		} catch (XPathExpressionException e) {
			System.out.println("异常:XPath表达式错误!");
			e.printStackTrace();
		}

		Book book = new Book(lang, title, author, year, price);
		return book;
	}

}

 

 

上面的测试类所使用的XML文件

文件名      :  bookstore.xml

文件路径  :  与上面的两个类放到同一目录下

<?xml version="1.0" encoding="gbk"?>
<bookstore>
	<book>
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>28.5</price>
	</book>
	<book>
		<title lang="en">Junit IN Action</title>
		<author>Robert J.</author>
		<year>2007</year>
		<price>58.5</price>
	</book>
	<book>
		<title lang="en">Struts 2 IN Action</title>
		<author>Rhodes K.R</author>
		<year>2005</year>
		<price>53.6</price>
	</book>
	<book>
		<title lang="en">Thinking of Java 4th</title>
		<author>Bruce Eckel</author>
		<year>2007</year>
		<price>78.9</price>
	</book>
	<book>
		<title lang="zh">修炼架构师之道</title>
		<author>陈杰驰</author>
		<year>2009</year>
		<price>63.5</price>
	</book>
	<book>
		<title lang="zh">哲学:心灵,宇宙</title>
		<author>ChenFeng</author>
		<year>2010</year>
		<price>96</price>
	</book>
</bookstore>

 

适用于项目中的写法(XML Node→Object)

解析一个XML节点,直接转换为一个对象并返回给调用者

 

解析XML返回对象的封装类

...

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import cn.chenfeng.common.ServiceException;

public class XMLParseManager {
	private XMLParseUtil xmlParser;

	public XMLParseManager() {
		try {
			xmlParser = new XMLParseUtil();
		} catch (ParserConfigurationException e) {
			throw new ServiceException("XMLParseManager@XMLParseManager(): "
					+ "Failed to create XML parser!" + e);
		}
	}

	/**
	 * 初始化方法,通过文件对象初始化XML解析器和文档对象
	 * 
	 * @param xmlParser
	 * @param document
	 * @param file
	 * @see [类、类#方法、类#成员]
	 */
	private Document getDocument(File file) {
		Document document = null;
		try {
			document = xmlParser.parseDocument(file);
		} catch (IllegalArgumentException e) {
			throw new ServiceException("XMLParseManager@getDocument: "
					+ "An illegal or inappropriate argument!" + e);
		} catch (SAXParseException e) {
			throw new ServiceException("XMLParseManager@getDocument: "
					+ "XML file error, can not parse!" + e);
		} catch (SAXException e) {
			throw new ServiceException("XMLParseManager@getDocument: "
					+ "There is a SAXException!" + e);
		} catch (IOException e) {
			throw new ServiceException("XMLParseManager@getDocument: "
					+ "There is an IOException!" + e);
		}

		return document;
	}

	/**
	 * 获取节点的值
	 * 
	 * @return nodeValue
	 * @see [类、类#方法、类#成员]
	 */
	private String getNodeValue(Node node, String xpath) {
		String nodeValue = null;
		try {
			nodeValue = xmlParser.getNodeStringValue(node, xpath);
		} catch (XPathExpressionException e) {
			throw new ServiceException("XMLParseManager@getNodeValue: "
					+ "XPath expression [" + xpath + "] error!" + e);
		}
		return nodeValue;
	}

	/**
	 * 根据作者姓名获取书籍
	 * 
	 * @param file
	 *            XML文件对象
	 * @param name
	 *            书籍作者姓名
	 * @return myBook
	 * @see [类、类#方法、类#成员]
	 */
	public Book getBookByAuthor(File file, String name) {
		Book myBook = null;

		if (null != file) {
			Document doc = getDocument(file);
			if (null != doc) {
				/*
				 * [author='" + name + "'] 表示只取author为name参数值的book节点
				 */
				String title = getNodeValue(doc, "//book[author='" + name
						+ "']/title");
				String lang = getNodeValue(doc, "//book[author='" + name
						+ "']/title/@lang");
				String author = getNodeValue(doc, "//book[author='" + name
						+ "']/author");
				String year = getNodeValue(doc, "//book[author='" + name
						+ "']/year");
				String price = getNodeValue(doc, "//book[author='" + name
						+ "']/price");
				myBook = new Book(lang, title, author, year, price);
			}
		} else {
			throw new ServiceException("XMLParseManager@getBookByAuthor: "
					+ "File is null!");
		}

		return myBook;
	}

}
 

 

上面类的单元测试类

...

import java.io.File;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class XMLParseManagerTest {
	XMLParseManager xmlMgr;

	@Before
	public void setUp() throws Exception {
		xmlMgr = new XMLParseManager();
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testGetMyBook() {
		String path = XMLParseManager.class.getResource("bookstore.xml")
				.getPath();
		File xmlfile = new File(path);
		Book actualBook = xmlMgr.getBookByAuthor(xmlfile, "ChenFeng");
		Assert.assertNotNull(actualBook);

		Book expectedBook = new Book("zh", "哲学:心灵,宇宙", "ChenFeng", 2010, 96.0);
		Assert.assertEquals(expectedBook, actualBook);
	}
}

 

使用到的Bean类

...

package cn.chenfeng.XML.xpath;

/**
 * Book类
 * 
 * @author ChenFeng
 * @version [版本号, 2009-12-21]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class Book {
	private String lang;

	private String title;

	private String author;

	private int year;

	private double price;

	public Book() {
	}

	public Book(String lang, String title, String author, String year,
			String price) {
		this.lang = lang;
		this.title = title;
		this.author = author;
		this.year = (int) Integer.valueOf(year);
		this.price = (double) Double.valueOf(price);
	}

	public Book(String lang, String title, String author, int year, double price) {
		this.lang = lang;
		this.title = title;
		this.author = author;
		this.year = year;
		this.price = price;
	}

	public String getLang() {
		return lang;
	}

	public void setLang(String lang) {
		this.lang = lang;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public int getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = (int) Integer.valueOf(year);
	}

	public void setYear(int year) {
		this.year = year;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = (double) Double.valueOf(price);
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public boolean equals(Object object) {
		Book b = (Book) object;
		if (this.lang.equals(b.getLang()) && this.title.equals(b.getTitle())
				&& this.author.equals(b.getAuthor())
				&& this.year == b.getYear() && this.price == b.price) {
			return true;
		}
		return false;
	}

	public String toString() {
		StringBuffer buf = new StringBuffer("");
		buf.append("Book{\n").append("  lang=").append(lang)
				.append("\n  title=").append(title).append("\n  author=")
				.append(author).append("\n  year=").append(year)
				.append("\n  price=").append(price).append("\n}");
		return buf.toString();
	}
}

 

 

 完!

 

 

9
1
分享到:
评论

相关推荐

    xpath解析xml

    在本篇文章中,我们将深入探讨如何利用XPath来解析XML文件,并且会提及如何通过XPath操作Map集合,从而避免过多地生成Java Bean类。 首先,理解XML文档的结构至关重要。XML是一种标记语言,用于存储数据,其结构...

    Java中使用xpath获取xml中的数据

    要使用XPath在Java中解析XML,我们需要引入以下库: 1. `javax.xml.xpath`:这个包提供了XPath API,包括XPathFactory、XPath和XPathExpression等类。 2. `javax.xml.parsers`:这个包包含了DocumentBuilderFactory...

    xpath读取XML节点

    2. **读取XML文件**:使用`SAXBuilder`类解析XML文件,创建一个`Document`对象,这是JDOM中的XML文档模型。 ```java File xmlFile = new File("path_to_your_xml_file"); SAXBuilder builder = new SAXBuilder(); ...

    xml-dom4j解析工具类

    在实际应用中,这样的工具类可能会包含更多的功能,比如创建、修改或删除XML节点,以及使用XPath表达式进行快速定位。XPath是一种在XML文档中查找信息的语言,它允许我们通过路径表达式来选取节点,大大提高了查询...

    java Dom4j 无敌连环解析XML工具类

    这个XMLUtil工具类包含了解析XML文件、获取根元素、读取属性值、遍历子元素以及使用XPath查找元素等常用操作。你可以根据实际需求扩展此工具类,添加更多的功能,例如创建新的XML文档、修改现有元素等。 使用这个...

    XPath解析工具

    在本案例中,我们讨论的是一个使用C#编写的XPath解析工具,该工具能够帮助开发者更方便地操作XML文档,提取所需的数据。 XPath工具的主要功能可能包括以下几点: 1. **节点选取**:XPath表达式可以用来选择XML文档...

    Dom4j 、XPath解析Xml所需的jar包和dom4j API

    在Java编程中,解析XML文档通常需要借助库,如DOM4J和XPath。DOM4J是一个灵活且功能强大的开源Java XML API,它提供了XML的读取、写入、修改和遍历等功能。XPath则是W3C标准中的一个查询语言,用于在XML文档中查找...

    JDOM解析XML

    要使用JDOM解析XML,首先需要将JDOM的jar文件(如jdom.jar)添加到项目的类路径中。此外,由于XML解析通常涉及到其他库,如XPath解析和DTD处理,我们看到压缩包中还包含了一些其他相关的jar文件: 1. xalan.jar:...

    XML通用解析工具类

    1. 解析XML文件:提供方法读取XML文件并将其解析为易于操作的数据结构。 2. 创建XML:反向操作,从数据结构生成XML字符串或文件。 3. 查询和修改:支持XPath表达式,允许快速查找和修改XML文档中的数据。 4. 错误...

    使用JDOM解析XML文件

    本篇文章将深入探讨如何使用JDOM解析XML文件。 首先,我们需要理解JDOM的基本结构。JDOM通过Document对象表示整个XML文档,Element代表XML元素,Attribute表示元素属性,Text表示元素内的文本内容。这些类构成了...

    xpath解析

    XPath(XML Path Language)是一种在XML文档...`XPathGetResultAction.java`和`zxccp-das-dfs-emf.xml`这两个文件的结合,为我们提供了一个实际应用XPath解析XML的实例,可以帮助我们更好地学习和掌握XPath的相关知识。

    支持xpath的高效xml解析库源代码

    同时,它的解析算法经过优化,能快速地解析XML文档,即使面对大型XML文件也能保持良好的性能。 **源代码结构** 在提供的压缩包中,我们可以看到以下几个主要部分: 1. **Makefile** - 用于构建项目的配置文件,...

    vtd-xml XML解析工具

    在Java环境中,XimpleWare公司提供的VTD-XML库包含了一系列API,如`VTDGen`用于解析XML文档并生成VTD索引,`AutoPilot`用于导航XML结构,以及`VTDNav`接口,它是核心的导航类,提供了各种方法来访问和操作XML元素和...

    dom4j 工具类 使用例子

    在这个"dom4j工具类使用例子"中,我们将深入探讨如何利用DOM4J进行XML处理。 首先,`Dom4jUtil.java`可能是包含DOM4J实用方法的类。这个类可能包括了创建、查询、修改XML文档的各种静态方法。例如,可能会有用于...

    xml 文件解析,可以在vc中直接使用的简易xml解析工具,方便简单快截

    在Visual C++(简称VC)环境下,为了处理XML文件,开发者通常会使用特定的库或者API来解析XML文档。本篇文章将详细介绍如何在VC中使用简易XML解析工具,以实现快速、便捷地读取和操作XML文件。 首先,理解XML的基本...

    dom+xpath读取xml并导入oracle.rar

    《DOM与XPath解析XML并导入Oracle数据库的深度实践》 在现代软件开发中,XML(eXtensible Markup Language)作为一种通用的数据交换格式,广泛应用于系统间的通信与数据存储。而DOM(Document Object Model)与...

    XML文件解析封装工具类

    1. 使用DOM解析XML字符串,得到`Document` 对象。 2. 遍历`Document` 的节点,根据节点的名称和值创建相应的Java对象实例。 3. 调用`XmlObject` 中的setter方法设置对象属性。 4. 如果有嵌套的XML结构,递归调用解析...

    MFC 解析XML类和Markup解析XML文件实例

    这两个类提供了解析XML文档和处理XML事件的能力,使得开发者能够在Visual C++环境中方便地操作XML数据。本文将深入探讨这两个类以及如何使用它们来解析和操作XML文件。 首先,`CXMLDOMDocument` 是基于MSXML...

    JAVA JAXB 解析XML嵌套子节点为字符串

    使用JAXB解析XML时,我们首先需要创建一个Java类模型,这个模型反映了XML文档的结构。每个XML元素对应一个Java类,类的属性对应元素的属性或子元素。例如,如果XML中有以下结构: ```xml &lt;text&gt;Some text here ...

    java解析xml生成json对象

    3. **测试工具类**:找到项目中的工具类文件,它应该包含一个方法用于解析XML并生成JSON对象。这个方法可能接受XML文件的路径作为参数,然后使用选择的XML解析器(如DOM或SAX)读取文件,接着使用JSON库将解析出的...

Global site tag (gtag.js) - Google Analytics