import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.io.*;
import java.util.*;
public class StationNumInfo {
public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = new FileInputStream("WebRoot/WEB-INF/StationNumInfo.xml");
Document document = db.parse(is);
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
XPathExpression expr = xp.compile("//station[value='123']/name/text()");
Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
//System.out.println(nodes.item(i).getNodeName());
System.out.println(nodes.item(i).getNodeValue());
}
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<StationNum>
<station>
<value>123</value>
<name>好的</name>
</station>
</StationNum>