java中通常需要将一些客户端设置项写在配置文件中,以避免重复编译导致的繁琐
xml文件:config.xml
<!--?xml version="1.0" encoding="UTF-8" ?--> <config> <chartype>B</chartype> <classname>DatabaseLoggerFactory</classname> </config> 现在要读取该文件中的<chartype>标签的值B,自定义工具类如下: </chartype>
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; } } }