想这是XML:搜索
<lib>
<books type="paperback" name="A" />
<books type="pdf" name="B" />
<books type="hardbound" name="A" />
</lib>
会是怎样的XPath的代码,搜索类型=“简装”和名称=“A”的书吗? TIA。
目前我的代码看起来是这样的:
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class demo {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("xml.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
String version="fl1.0";
XPathExpression expr = xpath.compile("//books/type[@input="paperback"]/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.compile(“// books/type [@ input =”paperback“]/text()”)'也是无效的Java。 – 2009-09-22 06:48:45
悲伤但真实:Java是框架最依赖XML的语言,但它最不适合处理XML。 – 2009-09-22 06:51:09
是的,虽然你可以添加'<?xml version =“1.0”?>'。 – 2009-09-22 07:33:02