以下是一种遍历xml文件中Text属性的方法,其他属性可以依葫芦画瓢。
注: import dom4j
package src.xmltuil; import java.io.File; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class XmlUtil { public static void main(String[] args){ //读取xml文档 SAXReader saxReader=new SAXReader(); Document doc=null; try { doc =saxReader.read(new File("C:\\Users\\zxy\\Desktop\\build.xml")); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Element root = doc.getRootElement(); if(root == null) System.out.println( "el = null"); for ( Iterator it =root.elementIterator(); it.hasNext(); ){ Element el = (Element) it.next(); //应该是输出所有属性 code?
if(el.isTextOnly()) System.out.println("##"+el.getName()+"--value=="+el.getTextTrim()); else print(el); } } /** * 递归显示文档内容 * @param els elements数组 */ public static void print(Element root){ if( root == null) return ; for ( Iterator<Element> it =root.elementIterator(); it.hasNext(); ){ Element el = (Element) it.next(); //应该是输出所有属性 if(el.isTextOnly()) System.out.println("##"+el.getName()+"--value=="+el.getTextTrim()); else print(el); } } }