package com.tudou.ajax.t1;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XpathByDom {
public static void main(String[] args) {
XpathByDom xj = new XpathByDom();
xj.calByXpathExpression();
}
/**
* 通过Xpath表达式计算员工平均工资
*/
public void calByXpathExpression() {
try {
File f = new File("WebRoot/xmls/employee.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
XPathFactory pathFactory = XPathFactory.newInstance();
XPath xpath = pathFactory.newXPath();
XPathExpression expre = xpath.compile("descendant::employee");
NodeList result = (NodeList) expre.evaluate(doc,XPathConstants.NODESET);
System.out.println("共有员工:" + result.getLength());
for (int i = 0; i < result.getLength(); i++) {
System.out.print("员工:"+ result.item(i).getChildNodes().item(1).getTextContent());
System.out.println(",工资:"+ result.item(i).getChildNodes().item(11).getTextContent());
}
XPathExpression expre1 = xpath.compile("sum(//employee/salary) div count(descendant::employee)");
Object result1 = expre1.evaluate(doc,XPathConstants.NUMBER);
System.out.println("----------------------");
System.out.println("平均工资:"+result1);
//销售额大于300000的工资有:公式为: "//sales[sale>300000"
// System.out.println("销售额大于" + num + "的员工有:" + e1.getText()
// + ",销售额为:" + e.getChild("sale").getText());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="scce001">
<name>Lan</name>
<dept>G3T05</dept>
<sex>famale</sex>
<birthday>
<year>1990</year>
<month>01</month>
<day>21</day>
</birthday>
<sales>
<year>2011</year>
<month>01</month>
<sale>70000</sale>
</sales>
<salary>3000</salary>
</employee>
<employee id="scce002">
<name>TuDou</name>
<dept>G3T05</dept>
<sex>male</sex>
<birthday>
<year>1989</year>
<month>01</month>
<day>24</day>
</birthday>
<sales>
<year>2011</year>
<month>01</month>
<sale>394000</sale>
</sales>
<salary>10000</salary>
</employee>
<employee id="scce003">
<name>Lee</name>
<dept>G3T05</dept>
<sex>male</sex>
<birthday>
<year>1989</year>
<month>09</month>
<day>03</day>
</birthday>
<sales>
<year>2011</year>
<month>01</month>
<sale>188880</sale>
</sales>
<salary>6000</salary>
</employee>
</employees>