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;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值