【发布时间】:2018-11-02 16:40:01
【问题描述】:
我有一个如下所示的 XHTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="sample" content="Just for sample"/>
<title/>
</head>
<body>
<h1>Sample Heading</h1>
<p align="left">XHTML and HTML are relatives.<a href="http://www.google.com">Google</a>
</p>
</body>
</html>
我想使用 Java 中的 XPath 表达式从 <p> 中提取 align 的属性值。所以,我尝试使用这段代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("TestFile.xhtml");
//Create XPath
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath Inst= xpathfactory.newXPath();
NodeList nodes = (NodeList)Inst.evaluate("//p/@align",doc,XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i)
{
Element e = (Element) nodes.item(i);
System.out.println(e);
}
在 Java 代码中。但我没有得到任何输出。即使我只写//body,也不会提取任何内容。谁能告诉我我在这里做错了什么?对代码进行任何编辑都会有所帮助。
【问题讨论】: