背景
感觉忙了好几天,但是回头看看却什么也没有忙
唯有写博客才觉得充实
之前看一个框架很有意思,将很多配置文件都写到xml文件中,如果系统中使用到读取xml中的配置文件
为什么不用properties这样的配置文件,我感觉是中文的问题
所以我把自己项目的config.properties也转换为config.xml这样的配置文件,这样增加备注也中文也方便查看
配置文件在classpath路径下:
<?xml version="1.0" encoding="UTF-8"?>
<root name="root">
<!-- 日志发送地址 -->
<prop name="SPBMJCBZ">1</prop>
<!--本地生成pdf下载地址 -->
<prop name="downloadpath">http://localhost:8010/system2/</prop>
<!-- linux系统当前保存路径 -->
<prop name="linux_path">/home/webapps/</prop>
<!-- 日志存储路径-->
<prop name="commonslog">/home/tmp/</prop>
<prop name="catalinalog">OFD</prop>
<prop name="localhostlog">OFD</prop>
</root>
读取
package com.hangxin.basic.util;
import java.io.IOException;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class XMLUtils {
/**
*
* @param attr 对应的name属性
* @return
*/
public static String getValueByName(String attr) {
try {
String text = null;
Resource cr = new ClassPathResource("config.xml");
SAXReader saxReader = new SAXReader();
// 读取文件
Document read;
read = saxReader.read(cr.getInputStream());
// 获取根节点
Element rootElement = read.getRootElement();
Iterator<Element> itertor = rootElement.elementIterator();
while (itertor.hasNext()) {
Element element = itertor.next();
if (attr.equals(element.attribute("name").getValue())) {
text = element.getText();
break;
}
}
return text;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
System.out.println(getValueByName("softname"));
}
}
上面便是对xml的读取
希望对你有所帮助!