在Java中使用Jdom读取xml配置文件

本文介绍了一个使用Java实现的手写XML解析器,该解析器利用JDOM和Jaxen库来解析WebConfig.xml配置文件,并从中提取特定的服务URL。通过XPath表达式定位目标节点,实现了配置信息的有效获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现有一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 {
	//从文档中解析对应的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");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值