Java中Jdom解析XML
JDOM与DOM类似,也是一组用于解析XML的API,它本身不是一个解析器,默认的它内置了Apache的Xerces解析器;
JDOM与DOM不同的是,DOM是跨语言的一套API,Java世界中有很多DOM的解析器,同样的.Net中也一样内置了DOM的实现,但是JDOM是专门为Java打造的一批API
JDOM采用了Java中的Collection架构来封装集合,是Java爱好者更加熟悉的模式。
sax解析: http://www.cnblogs.com/gavinYang/p/3505543.html
dom4j解析: http://www.cnblogs.com/gavinYang/p/3505535.html
dom解析: http://www.cnblogs.com/gavinYang/p/3505523.html
JAVA代码:
1 package com.test; 2 3 import java.io.File; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 import org.jdom.Document; 8 import org.jdom.Element; 9 import org.jdom.input.SAXBuilder; 10 11 public class JdomXML { 12 13 public static void main(String[] args) { 14 File file = new File("e:/People.xml"); 15 SAXBuilder builder = new SAXBuilder(); 16 try { 17 Document document = builder.build(file); 18 Element root = document.getRootElement(); 19 List<Element> list = root.getChildren(); 20 List<People> peoples = new ArrayList<People>(); 21 People people = null; 22 for (Element peopleElement : list) { 23 people = new People(); 24 if(null != peopleElement.getAttribute("id")){ 25 people.setId(peopleElement.getAttribute("id").getValue()); 26 } 27 List<Element> childPeopleElements = peopleElement.getChildren(); 28 for (Element childPeopleElement : childPeopleElements) { 29 if ("Name".equals(childPeopleElement.getName())) { 30 people.setEnglishName(childPeopleElement.getAttributeValue("en")); 31 people.setName(childPeopleElement.getText()); 32 } 33 else if ("Age".equals(childPeopleElement.getName())) { 34 people.setAge(childPeopleElement.getText()); 35 } 36 } 37 peoples.add(people); 38 } 39 for (People p : peoples) { 40 System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getEnglishName()+"\t"+p.getAge()); 41 } 42 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 47 } 48 49 }
People对象:
1 package com.test; 2 3 public class People { 4 private String id; 5 private String name; 6 private String englishName; 7 private String age; 8 public String getId() { 9 return id; 10 } 11 public void setId(String id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public String getEnglishName() { 21 return englishName; 22 } 23 public void setEnglishName(String englishName) { 24 this.englishName = englishName; 25 } 26 public String getAge() { 27 return age; 28 } 29 public void setAge(String age) { 30 this.age = age; 31 } 32 33 }
xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <PeopleList> 3 <People id="1"> 4 <Name en='zhangsan'>张三</Name> 5 <Age>20</Age> 6 </People> 7 <People id="2"> 8 <Name en='lisi'>李四</Name> 9 <Age>30</Age> 10 </People> 11 </PeopleList>