Java JDom 解析xml

JDOM在解析XML在代码量之上比之前的方法(DOM和SAX要少很多了)。

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 JDOMException, IOException{
		SAXBuilder builder = new SAXBuilder(); 
		Document doc = builder.build(new File("D:"+File.separator+"test.xml")); 
		Element foo = doc.getRootElement(); 
		List allChildren = foo.getChildren(); 
		for(int i=0;i<allChildren.size();i++) { 
		    System.out.print("NO:" + ((Element)allChildren.get(i)).getChild("NO").getText()); 
		    System.out.print("\tid:"+((Element)allChildren.get(i)).getChild("NO").getAttributeValue("id"));
		    System.out.println("\tAddress:" + ((Element)allChildren.get(i)).getChild("NAME").getText()); 
		} 
	}

猜你喜欢

转载自gaofulai1988.iteye.com/blog/2262680