Java Dom4j 解析XML

Dom4j和JDom是很相似的,用起来十分方便。

XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>    
<Students>
   <student>
       <NO id="123">123456</NO>
	   <NAME>abc</NAME>
   </student>
   <student>
   
       <NO id="234">456789</NO>
	   <NAME>def</NAME>
   </student>
</Students>


代码如下:
public static void main(String args[]) throws DocumentException{
		File f = new File("D:"+File.separator+"test.xml"); 
		SAXReader reader = new SAXReader(); 
		Document doc = reader.read(f); 
		Element root = doc.getRootElement(); 
		Element foo;
		// 查找指定的标签
		Iterator i = root.elementIterator("student");
		while(i.hasNext()) { 
			  // 获取它的标签元素
	          foo = (Element) i.next(); 
		      System.out.print("NO:" + foo.elementText("NO")); 
		      System.out.print("\tNAME:"+foo.elementText("NAME"));
		      System.out.println("\tid:"+foo.element("NO").attributeValue("id"));
		}
	}

你可能感兴趣的:(java,xml,dom4j,dom4j)