現有一Web項目,在src目錄下有設定檔WebConfig.xml
<?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 {//從文檔中解析對應的urlpublic 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");}}