现有一Web项目,在src目录下有配置文件WebConfig.xml
手写XML解析类,前提需要在项目中添加jdom-2.0.5.jar、jaxen-1.1.1.jar 两个jar包
<?xml version="1.0" encoding="UTF-8"?>
<services>
<service name="apnServer" url="http://192.168.1.89:7070/"/>
</services>
手写XML解析类,前提需要在项目中添加jdom-2.0.5.jar、jaxen-1.1.1.jar 两个jar包
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPath;
public class XMLParse {
//从文档中解析对应的url
public static String getContent(String attributeName){
SAXBuilder sax = new SAXBuilder();
Document doc;
try {
doc = sax.build(XMLParse.class.getResource("/").getPath()+"WebConfig.xml");
Element rootEle = doc.getRootElement();
List serviceList = XPath.selectNodes(rootEle, "//services/service");
if(serviceList!=null&&serviceList.size()>0){
for (int i = 0; i < serviceList.size(); i++) {
Element service=(Element)serviceList.get(i);
if(attributeName!=null&&attributeName.equals(service.getAttributeValue("name"))){
return service.getAttributeValue("url");
}
}
}else{
return null;
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
在其他类中可以进行调用
public class GetPostUtil {
public static String androidPushNotificationURL = "";
static{
androidPushNotificationURL=XMLParse.getContent("apnServer");
}
}