JAVA 用dom4j读取xml

来源:互联网 发布:淘宝宝贝手机排名查询 编辑:程序博客网 时间:2024/06/05 20:26

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的类库,特别是它可以加以选择条件来选取某一节点,这个非常好用。
	
				
		
原创粉丝点击