xpath 学习
2014-12-19 15:07 MarkQ 阅读(155) 评论(0) 收藏 举报[java] view plaincopy
import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XpathTest {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:/Users/Administrator/Desktop/test.xml");
System.out.println(doc.getChildNodes().getLength());
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath
.compile("//name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}
setNamespaceAware
public void setNamespaceAware(boolean awareness)
- 指定由此代码生成的解析器将提供对 XML 名称空间的支持。默认情况下,其值设置为
false。 - 参数:
awareness- 如果生成的解析器将提供对 XML 名称空间的支持,则为 true;否则为 false。
DocumentBuilder :
定义 API, 使其从 XML 文档获取 DOM 文档实例。使用此类,应用程序员可以从 XML 获取一个 Document。
此类的实例可以从 DocumentBuilderFactory.newDocumentBuilder() 方法获取。获取此类的实例之后,将可以从各种输入源解析 XML。这些输入源有 InputStreams、Files、URL 和 SAX InputSources。
注意,此类重用了 SAX API 中的一些类。这并不要求底层 DOM 实现的实现者使用 SAX 解析器将 XML 文档解析为 Document。它仅要求该实现使用这些现有的 API 与应用程序交流。
parse
public Document parse(File f) throws SAXException, IOException
- 将给定文件的内容解析为一个 XML 文档,并且返回一个新的 DOM
Document对象。如果File为null,则抛出IllegalArgumentException。
Document 接口表示整个 HTML 或 XML 文档。从概念上讲,它是文档树的根,并提供对文档数据的基本访问。
因为元素、文本节点、注释、处理指令等不能存在于 Document 的上下文之外,所以 Document 接口还包含所需的创建这些对象的工厂方法。所创建的 Node 对象具有 ownerDocument 属性,该属性将 Node 对象与创建这些对象时的上下文所属的 Document 关联起来。
编译 XPath 表达式供以后计算使用。
浙公网安备 33010602011771号