dom4j是一個很好用的讀取xml的類庫,特別是它可以加以選擇條件來選取某一節點,這個非常好用。
1、產生Document檔案。
/** * @param xmlFilePath xml檔案路徑 * @return Document對象 */ public static Document getDocument(String xmlFilePath) { SAXReader reader = new SAXReader(); Document document = null; try { InputStream in = AnalyticalXML.class.getResourceAsStream(xmlFilePath); document = reader.read(in); } catch (DocumentException e) { System.out.println("讀取classpath下xmlFileName檔案發生異常,請檢查CLASSPATH和檔案名稱是否存在!"); e.printStackTrace(); } return document; }
2、
/** * 效能低 * 建立時間:2012-3-26 * @author WQL * @param xmlFileName * @param conditions /data/equip[@itemid1=41] [@itemid2=51] 兩個條件 */ public static void xml_Armor_equip_config(String xmlFileName,String conditions){ //TODO: Document document = AnalyticalXML.getDocument(xmlFileName); List list = document.selectNodes(conditions); StringBuffer sb=new StringBuffer(0); Iterator iter = list.iterator(); while(iter.hasNext()){ Element ep = (Element) iter.next(); for(Iterator it=ep.attributeIterator();it.hasNext();){Attribute attribute = (Attribute) it.next();String name=attribute.getName();String value=attribute.getValue();sb.append(" "+name+"="+value);} sb.append("\r"); Iterator iterss = ep.elementIterator("material"); while (iterss.hasNext()) { Element kp = (Element) iterss.next(); sb.append(" <material "); String itemtype = kp.attributeValue("itemtype"); sb.append(" itemtype:"+itemtype); String itemid = kp.attributeValue("itemid"); sb.append(" itemid:"+itemid); String itemcount = kp.attributeValue("itemcount"); sb.append(" itemcount:"+itemcount); sb.append("\r"); } Iterator rivet = ep.elementIterator("rivet"); while (rivet.hasNext()) { sb.append(" <rivet "); Element np =(Element) rivet.next(); String x=np.attributeValue("x"); sb.append("x:"+x); String y=np.attributeValue("y"); sb.append("y:"+y); } System.out.println(sb.toString()); sb.append("\r\n"); } }
3、調用
xml_Armor_equip_config("/XML/armor_equip_config.xml","/data/equip[@itemid1=41][@itemid2=51]");
dom4j是一個很好用的讀取xml的類庫,特別是它可以加以選擇條件來選取某一節點,這個非常好用。