在 jdk1.4 中使用 Xpath 解析 XML 文件 [英] Parsing XML file using Xpath in jdk1.4

查看:23
本文介绍了在 jdk1.4 中使用 Xpath 解析 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了以下从 XML 文件中提取值的简单解决方案.

I found the following easy solution to extracting values from XML file.

import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class XPathExample {

  public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("c:/temp/books.xml");

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr 
     = xpath.compile("//book[author='Neal Stephenson']/title/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue()); 
    }

  }

}

这使用 xpath 从以下 xml 中提取所有作者是 Neal Stephenson 的书名

This uses xpath to extract all books title where the author is Neal Stephenson from the following xml

<inventory>
<book year="2000">
    <title>Snow Crash</title>
    <author>Neal Stephenson</author>
    <publisher>Spectra</publisher>
    <isbn>0553380958</isbn>
    <price>14.95</price>
</book>

<book year="2005">
    <title>Burning Tower</title>
    <author>Larry Niven</author>
    <author>Jerry Pournelle</author>
    <publisher>Pocket</publisher>
    <isbn>0743416910</isbn>
    <price>5.99</price>
</book>

<book year="1995">
    <title>Zodiac</title>
    <author>Neal Stephenson</author>
    <publisher>Spectra</publisher>
    <isbn>0553573862</isbn>
    <price>7.50</price>
</book>

<!-- more books... -->

</inventory>

现在这在 JDK5 上运行良好,但我使用的是 jdk 1.4这可以转换为 java 1.4 等价物吗?

Now this works fine on JDK5 but i am using jdk 1.4 Can this be converted to the java 1.4 equivalent?

我要做的就是从 xml 元素中提取一个值.例如,在上面的 xml 中,我只想要相当于 getElementByTag("title") 的东西.

All i am trying to do is extract a value from an xml element. For example, in the above xml, i just want something that is the equivalent of getElementByTag("title").

谢谢

推荐答案

快速 google 导致了类似 thisthis 确认 JAXP 可以单独下载并运行在 JDK 1.4.2 之上.您可能会遇到 apache 链接中提到的配置问题.祝你好运!

Quick google resulted in links like this and this which confirm that JAXP can be downloaded separately and run on top of JDK 1.4.2. You might run into configuration problems as mentioned in the apache link. Good luck!

这篇关于在 jdk1.4 中使用 Xpath 解析 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆