XML文件如下:person.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <employees> 
  3.     <employee> 
  4.         <name pinyin="zhangsan">张三</name> 
  5.         <sex>m</sex> 
  6.         <age>30</age> 
  7.     </employee> 
  8.     <employee> 
  9.         <name pingyin="tom">tom</name> 
  10.         <sex>w</sex> 
  11.         <age>20</age> 
  12.     </employee> 
  13. </employees> 

使用jdom来解析必须要有jdom的插件包,附件中已经上传

JAVA实现代码

 

 

  1. import java.io.File; 
  2. import java.io.IOException; 
  3. import java.util.List; 
  4.  
  5. import org.jdom.Attribute; 
  6. import org.jdom.Document; 
  7. import org.jdom.Element; 
  8. import org.jdom.JDOMException; 
  9. import org.jdom.input.SAXBuilder; 
  10.  
  11.  
  12. public class JDOMxml { 
  13.  
  14.     public static void main(String[] args) { 
  15.         String path = Class.class.getResource("/").getPath(); 
  16.         SAXBuilder builder = new SAXBuilder(); 
  17.         try { 
  18.             Document doc = builder.build(new File(path+"person.xml")); 
  19.  
  20.             Element foo = doc.getRootElement();  
  21.  
  22.             List allChildren = foo.getChildren();  
  23.  
  24.             for(int i=0;i<allChildren.size();i++) { 
  25.  
  26.                 Element it = (Element) allChildren.get(i);//获得的是employee节点 
  27.                 Element its = it.getChild("name"); 
  28.                 List list = its.getAttributes(); 
  29.                 for (int j = 0; j < list.size(); j++) { 
  30.                     Attribute att = (Attribute) list.get(j); 
  31.                     System.out.println("属性:"+att.getValue()); 
  32.  
  33.                 } 
  34.  
  35. //              System.out.println(its.getAttributeValue("name", "pinyin")); 
  36.  
  37.                 System.out.println("名字:" + ((Element)allChildren.get(i)).getChild("name").getText());  
  38.  
  39.                 System.out.println("性别:" + ((Element)allChildren.get(i)).getChild("sex").getText()); 
  40.  
  41.                 System.out.println("年龄:" + ((Element)allChildren.get(i)).getChild("age").getText());  
  42.  
  43.             }  
  44.         } catch (JDOMException e) { 
  45.             // TODO Auto-generated catch block 
  46.             e.printStackTrace(); 
  47.         } catch (IOException e) { 
  48.             // TODO Auto-generated catch block 
  49.             e.printStackTrace(); 
  50.         }  
  51.     }