XMLUtil工具类读取XML或properties格式的配置文件

java中通常需要将一些客户端设置项写在配置文件中,以避免重复编译导致的繁琐
xml文件:config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<config>
    <charType>B</charType>
    <className>DatabaseLoggerFactory</className>
</config>
现在要读取该文件中的<charType>标签的值B,自定义工具类如下:

public class XMLUtil {
//该方法用于从XML配置文件中读取标签值
public static String getChartType() {
try {
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File(“config.xml”));
//获取包含charType类型的文本节点,此处可以改为className
NodeList nl = doc.getElementsByTagName(“chartType”);
Node classNode = nl.item(0).getFirstChild();
String chartType = classNode.getNodeValue().trim();
return chartType;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}



版权声明:本文为zhang999zhi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。