1、目录结构
2、test.xml
<?xml version="1.0" encoding="GBK"?>
<config>
<type>
<field><start>K001</start><end>002</end><description>描述1</description></field>
<field>
<start>K002</start>
<end>003</end>
<description>描述2</description>
</field>
</type>
<orderInfo>
<store>店铺名称</store>
<adress>XX路6543号</adress>
<tel>联系方式</tel>
<inter>
<rd><no>001</no><book>书名</book><price>单价</price><mark>备注</mark></rd>
<rd>
<no>002</no>
<book>书名</book>
<price>单价</price>
<mark>备注</mark>
</rd>
</inter>
</orderInfo>
</config>
3、XMLTest.java
package com.lijy.util;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class XMLTest {
private static Map typeIdMap = new HashMap();
private static Map typeNameMap = new HashMap();
public static void loadConfig() {
Document document = null;
/*
* 读取xml文件
*/
try {
document = read("/com/lijy/util/test.xml");
} catch (DocumentException e) {
e.printStackTrace();
}
List typeList = document.selectNodes("//config/type/field");
for (int i = 0; i < typeList.size(); i++) {
Element field = (Element) typeList.get(i);
typeIdMap.put(getSubElementText(field, "start"), getSubElementText(field, "end"));
typeNameMap.put(getSubElementText(field, "start"), getSubElementText(field, "description"));
}
List orderList = document.selectNodes("//config/orderInfo");
for (int i = 0; i < orderList.size(); i++) {
Element field = (Element) orderList.get(i);
String store = getSubElementText(field, "store").trim();
String adress = getSubElementText(field, "adress").trim();
String tel = getSubElementText(field, "tel").trim();
System.out.println(store);
System.out.println(adress);
System.out.println(tel);
List reList = field.selectNodes("inter/rd");
Map temp = new HashMap();
for (int j = 0; j < reList.size(); j++) {
Element item = (Element) reList.get(j);
System.out.println(getSubElementText(item, "no"));
System.out.println(getSubElementText(item, "book"));
System.out.println(getSubElementText(item, "price"));
System.out.println(getSubElementText(item, "mark"));
}
}
}
public static Document read(String path) throws DocumentException {
SAXReader reader = new SAXReader();
InputStreamReader is = new InputStreamReader(new XMLTest().getClass().getResourceAsStream(path), Charset.forName("GBK"));
Document document = reader.read(is);
return document;
}
public static String getSubElementText(Element element, String name) {
if (element == null) {
return null;
}
Iterator iterator = element.elementIterator(name);
if (iterator.hasNext()) {
Element temp = (Element) iterator.next();
return temp.getText();
} else {
return null;
}
}
public static void main(String[] args) {
loadConfig();
System.out.println(typeIdMap);
System.out.println(typeNameMap);
}
}
4、运行结果:
店铺名称XX路6543号联系方式001书名单价备注002书名单价备注{K002=003, K001=002}{K002=描述2, K001=描述1}