JDOM
JDOM是什么:
To provide a complete, Java-based solution for accessing, manipulating, and outputting XML data from Java code.
JDOM与其他几种XML解析工具的比较:
DOM VS SAX VS JDOM VS DOM4J: http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/17/3082949.html
结合文章的结论,对于小型xml文件, 而且调用不频繁的操作, 可以直接使用JDOM来完成。
示例:
以idc解析xml为例
xml:
<?xml version="1.0" encoding="UTF-8"?> <Agent> <Region> <RegionName>beijing</RegionName> <IDC> <IDCName>CY</IDCName> <Item> <IP>192.168.121.0</IP> <MASK>255.255.255.0</MASK> </Item> <Item> <IP>192.168.122.0</IP> <MASK>255.255.255.0</MASK> </Item> </IDC> </Region> <Region> <RegionName>shanghai</RegionName> <IDC> <IDCName>HP</IDCName> <Item> <IP>192.168.63.0</IP> <MASK>255.255.255.0</MASK> </Item> </IDC> </Region> </Agent>
Java代码:
public static Idc parserXml(String fileName, String ip) { SAXBuilder builder = new SAXBuilder(); Idc resIdc = new Idc(); try { Document document = builder.build(fileName); Element sgagent = document.getRootElement(); List regionList = sgagent.getChildren("Region"); for (Object ele:regionList) { Element region = (Element) ele; List idcs = region.getChildren("IDC"); for (Object eleIdc:idcs) { Element idc = (Element)eleIdc; List items = idc.getChildren("Item"); for (Object eleItem:items) { Element item = (Element)eleItem; String idcIp = item.getChild("IP").getValue(); String idcMask = item.getChild("MASK").getValue(); int mask = IpUtil.convertMaskToInt(idcMask); if (IpUtil.checkSameSegment(ip, idcIp, mask)) { resIdc.region = region.getChild("RegionName").getValue(); resIdc.idc = idc.getChild("IDCName").getValue(); return resIdc; } } } System.out.println(region.getChild("RegionName").getName() + ":" + region.getChild("RegionName").getValue()); } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } resIdc.region = "unkown"; resIdc.idc = "unkown"; return resIdc; }