import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*; //Java基础包,包含各种IO操作
import java.util.*; //Java基础包,包含各种标准数据结构操作
import javax.xml.parsers.*; //XML解析器接口
import org.w3c.dom.*;
import com.happyelements.apollo.config.type.AppType;
import com.happyelements.apollo.util.ApolloCollectionsUtil;
public class ParseMemXML {
public static final Map<String, MemBean> memMap = ApolloCollectionsUtil.newMap();//将MemBean放到map中存放
//解析xml文件并将得到的实例放入map中
public static void initXMLFile(String filename) throws Exception {
// 为解析xml做准备
// 创建DocumentBuilderFactory实例,指定DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.out.println(pce);
// 出异常时输出异常信息,然后退出,下同
System.exit(1);
}
Document doc = null;
try {
doc = db.parse(filename);
} catch (DOMException dom) {
System.err.println(dom.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
// 下面是解析XML的全过程,
// 比较简单,先取根元素"memcaches"
Element root = doc.getDocumentElement();
// 取"memcache"元素列表
NodeList memcaches = root.getElementsByTagName("memcache");
for (int i = 0; i < memcaches.getLength(); i++) {
// 创建一个memcache的Bean实例
MemBean memBean = new MemBean();
// 依次取每个"memcache"元素
Element memcache = (Element) memcaches.item(i);
// 取memcache的type属性
memBean.setType(memcache.getAttribute("type"));
// 取"ip"元素,下面类同
NodeList ips = memcache.getElementsByTagName("ip");
if (ips.getLength() == 1) {
Element e = (Element) ips.item(0);
Text t = (Text) e.getFirstChild();
memBean.setIp(t.getNodeValue());
System.out.println(memBean.getIp());
}
NodeList prefixs = memcache.getElementsByTagName("prefix");
if (prefixs.getLength() == 1) {
Element e = (Element) prefixs.item(0);
Text t = (Text) e.getFirstChild();
memBean.setPrefix(t.getNodeValue());
System.out.println(memBean.getPrefix());
}
memMap.put(memBean.getType().toString(), memBean);
}
}
public static void main(String[] args) throws Exception {
ParseMemXML.initXMLFile("E:workplaceTool2WebRootWEB-INFmemconf.xml");
System.out.println(ParseMemXML.memMap.size());
MemBean memBean = ParseMemXML.memMap.get(AppType.AAAA.toString());
System.out.println("ip=====" + memBean.getIp());
System.out.println("prefix===" + memBean.getPrefix());
}
}