JAVA如何获取xml文件的某个配置节点内容
·
如果想要直接获取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;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)