`
berdy
  • 浏览: 509318 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

使用xpath解析xml时,出现IOException

阅读更多
今天在写尝试使用java中的xpath接口来解析xml数据时出现了IOException。

程序的源文件如下:
一个xml文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
	<book category="COOKING">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year>
		<price>30.00</price>
	</book>
	<book category="CHILDREN">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="WEB">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<author>Per Bothner</author>
		<author>Kurt Cagle</author>
		<author>James Linn</author>
		<author>Vaidyanathan Nagarajan</author>
		<year>2003</year>
		<price>49.99</price>
	</book>
	<book category="WEB">
		<title lang="zh">Learning XML</title>
		<author>Erik T. Ray</author>
		<year>2003</year>
		<price>39.95</price>
	</book>
</bookstore>

出现问题的java代码如下:
InputSource inputSource = new InputSource(new FileInputStream("test.xml"));
XPathFactory factory = XPathFactory.newInstance();
XPath path = factory.newXPath();
XPathExpression expr1 = path.compile("/bookstore/book/title/text()");
XPathExpression expr2 = path.compile("/bookstore/book/price/text()");
System.out.println(expr2.evaluate(inputSource, XPathConstants.STRING));
//在第二次调用evaluate()方法时,出现了IOException
System.out.println(expr1.evaluate(inputSource, XPathConstants.STRING));

跟踪了下源代码,在每次调用Object evaluate(InputSource source, QName returnType)这个方法时都会重新生成DocumentBuilder对象来parse InputSource,每次parse都会把整个文件都解析成dom树并load到内存中,然后关闭流。在第二次parse同一个Inputsource的时候便产生了IOException。于是将上面的代码改造了下便成功了。
try {
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = builderFactory.newDocumentBuilder();
	Document doc = builder.parse(new FileInputStream("test.xml"));
	XPathFactory factory = XPathFactory.newInstance();
	XPath path = factory.newXPath();
	XPathExpression expr1 = path.compile("/bookstore/book/title/text()");
	XPathExpression expr2 = path.compile("/bookstore/book/price/text()");
	System.out.println(expr1.evaluate(doc, XPathConstants.STRING));
	System.out.println(expr2.evaluate(doc, XPathConstants.STRING));
} catch (ParserConfigurationException e) {
	e.printStackTrace();
} catch (FileNotFoundException e) {
	e.printStackTrace();
} catch (SAXException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
} catch (XPathExpressionException e) {
	e.printStackTrace();
}



1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics