对java来说,xml太重要了,尤其是对于框架来说,配置文件上面的应用,xml可能是最多的方式
<book>
<category name="one_piece" description="海贼王">
<item name="Luffy" value="船长"/>
<item name="Zero" value="副船长"/>
</category>
</book>
首先造一个xml文档出来:(books.xml放在src路径下)
实例代码
package com.sunkq;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Config {
//遍历xml到map中,方便读取
private static Map items = new HashMap();
//读取xml只需要一次
static {
try {
loadConfig();
} catch (DocumentException e) {
e.printStackTrace();
}
}
//读入xml文件
private static void loadConfig() throws DocumentException {
Document document = null;
File file = null;
// 得到类的类装载器
ClassLoader loader = Config.class.getClassLoader();
// 先从当前类所处路径的根目录中寻找属性文件
URL url = loader.getResource("book.xml");
file = new File(url.getPath());
document =new SAXReader().read(file);
if (document != null) {
Element systemElement = document.getRootElement();
List catList = systemElement.elements("category");
for (Iterator catIter = catList.iterator(); catIter.hasNext();) {
Element catElement = (Element) catIter.next();
String catName = catElement.attributeValue("name");
List itemList = catElement.elements("item");
for (Iterator itemIter = itemList.iterator(); itemIter
.hasNext();) {
Element itemElement = (Element) itemIter.next();
String itemName = itemElement.attributeValue("name");
String value = itemElement.attributeValue("value");
items.put(catName + "." + itemName, value);
}
}
}
}
/**
*
* @描述:获取配置的值,根据需要可以扩展为其他类型的值
*/
public static String getString(String name) {
String value = (String) items.get(name);
return (value == null) ? "" : value;
}
public static void main(String[] args) {
System.out.println(getString("one_piece.Luffy"));
}
}
运行结果
船长