这是以下在 Java 中使用 XPath 解析 XML 的标准代码。我无法调试为什么我得到空值。我附上了java文件、xml文件和输出。如果有人能解释一下我哪里出错了,我将不胜感激。提前致谢!:)
XPathParser.java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class XPathParser {
public static void main(String args[]) throws Exception {
//loading the XML document from a file
DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
builderfactory.setNamespaceAware(true);
//XML read
DocumentBuilder builder = builderfactory.newDocumentBuilder();
Document xmlDocument = builder.parse("Stocks.xml");
// Creates a XPath factory
XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
//Creates a XPath Object
XPath xPath = factory.newXPath();
//Compiles the XPath expression
//XPathExpression xPathExpression_count = xPath.compile("count(//stock)");
XPathExpression xPathExpression = xPath.compile("//stock");
//Run the query and get a nodeset
Object result = xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
//Cast the result into a DOM nodelist
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
System.out.println(nodes.item(0));
for (int i=0; i<nodes.getLength();i++){
System.out.println(nodes.item(i).getNodeValue());
}
}
}
股票.xml
<?xml version="1.0" encoding="UTF-8"?>
<stocks>
<stock>
<symbol>ABC</symbol>
<price>10</price>
<quantity>50</quantity>
</stock>
<stock>
<symbol>XYZ</symbol>
<price>20</price>
<quantity>1000</quantity>
</stock>
</stocks>
输出:
2
[stock: null]
null
null