功能描述:根据指定的元素和属性,得到相关值。适用于Java项目中读取xml形式的配置文件。静态方法可以直接用ReadConfigXml.ReadConfig("httpserver", "url");调用。
<root>
<httpserver url="http://127.0.0.1:8080/Demo/Test.do" name= "某某接口"></httpserver>
</root>
xml例子
package com.util.config;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadConfigXml {
public static String getClassesPath() {
String classesPath = System.getProperty("user.dir");
File file= new File(classesPath);
return file.getAbsolutePath();
}
public static String ReadConfig(String key, String att) {
String keyvalue = "";
Map<String, Object> myattributes = new HashMap<>();
SAXReader reader = new SAXReader();
Document document = null;
try {
File file = new File(getClassesPath() + File.separator + "config" + File.separator + "config.xml");
document = reader.read(file);
} catch (DocumentException e) {
e.printStackTrace();
}
Element rootElement = document.getRootElement();
Element distElement = rootElement.element(key);
if (distElement != null) {
List<Attribute> attributes = distElement.attributes();
for (Attribute attribute : attributes) {
myattributes.put(attribute.getName(), attribute.getValue());
}
if (myattributes.containsKey(att)) {
keyvalue = myattributes.get(att).toString();
} else {
System.out.println("config.xml中" + key + "不存在属性" + att);
}
}
if (distElement == null) {
System.out.println("config.xml不存在" + key);
}
return keyvalue;
}
}
代码。