public class ReadConfigureXml {
private Element rootElement = null;
public Element getRootElement() {
return rootElement;
}
public ReadConfigureXml(String xmlName) {
SAXBuilder builder = new SAXBuilder();
try {
Document doc = builder.build(Thread.currentThread()
.getContextClassLoader().getResourceAsStream(xmlName));
rootElement = doc.getRootElement(); //返回根元素,然后用XPath通过这个根元素,直接获取xml文件里定义的数据
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用:
public class Crawler {
private String crawlId = null;
private static final String SERVER_FILE_NAME = "server.xml";
public void crawlerReg(IRegister reg) {
if (crawlId == null) {
Element ipElement = null;
Element portElement = null;
ReadConfigureXml read = new ReadConfigureXml(SERVER_FILE_NAME);
Element rootElement = read.getRootElement();
try {
ipElement = (Element) XPath.selectSingleNode(rootElement, "//configure/server/ip");//获得ip地址
portElement = (Element) XPath.selectSingleNode(rootElement, "//configure/server/register-port");//获得port号
} catch (JDOMException e) {
e.printStackTrace();
}
crawlId = reg.register(ipElement.getText(),Integer.parseInt(portElement.getText()));
System.out.println("CrawlId is : " + crawlId);
}
}
public static void main(String[] args) {
Crawler crawler = new Crawler();
IRegister reg = new RegisterImpl();
crawler.crawlerReg(reg);
}
}
<?xml version="1.0" encoding="utf-8"?>
<configure>
<server>
<ip>10.0.0.166</ip>
<register-port>5678</register-port>
<geturls-port></geturls-port>
</server>
</configure>