如果想要直接获取webconfig.xml里面某个配置文件的节点的内容,如何优雅的实现?
例如有个xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<webapp-configs>
<param name="IP" value="127.0.0.1"/>
<param name="PORT" value="8070"/>
</webapp-configs>
如何获取PORT的value是多少呢?
下面是代码:
public class WebappConfigUtil {
private final static String CONFIG_FILE_NAME = "/webapp-config.xml";
private Document configDocument;
private static WebappConfigUtil instance = new WebappConfigUtil();//得到配置文件的document对象
private WebappConfigUtil() {
SAXReader reader = new SAXReader();//创建一个读取xml文件的对象
try {
configDocument = reader.read(WebappConfigUtil.class
.getResourceAsStream(CONFIG_FILE_NAME));//括号内:查找具有给定名称的资源 括号外:得到document对象
} catch (DocumentException exp) {
configDocument = DocumentHelper.createDocument();
configDocument.addElement("webapp-configs");
}
}
public static String getParameter(String name) {
//读取wabapp-config.xml的字符串(大标签套小标签)
String xpath = "/webapp-configs/param[@name='" + name + "']/@value";
Node node = instance.configDocument.selectSingleNode(xpath);//找到节点
if (node == null) {
return "";
}
return node.getText();
}
public static void main(String[] args){
System.out.println(WebappConfigUtil.getParameter("PORT"));
}
}
如果想获取参数为name的所有节点的list,那么
public static List<String> getParameterList(String name) {
String xpath = "/webapp-configs/param[@name='" + name + "']/list/value";
List<?> nodes = instance.configDocument.selectNodes(xpath);
List<String> values = new ArrayList<String>();
for (Iterator<?> iter = nodes.iterator(); iter.hasNext();) {
Node node = (Node) iter.next();
values.add(node.getText());
}
return values;
}