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代码:
package com.test; import java.io.File;
import java.util.ArrayList;
import java.util.List; import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder; public class JdomXML { public static void main(String[] args) {
File file = new File("e:/People.xml");
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(file);
Element root = document.getRootElement();
List<Element> list = root.getChildren();
List<People> peoples = new ArrayList<People>();
People people = null;
for (Element peopleElement : list) {
people = new People();
if(null != peopleElement.getAttribute("id")){
people.setId(peopleElement.getAttribute("id").getValue());
}
List<Element> childPeopleElements = peopleElement.getChildren();
for (Element childPeopleElement : childPeopleElements) {
if ("Name".equals(childPeopleElement.getName())) {
people.setEnglishName(childPeopleElement.getAttributeValue("en"));
people.setName(childPeopleElement.getText());
}
else if ("Age".equals(childPeopleElement.getName())) {
people.setAge(childPeopleElement.getText());
}
}
peoples.add(people);
}
for (People p : peoples) {
System.out.println(p.getId()+"\t"+p.getName()+"\t"+p.getEnglishName()+"\t"+p.getAge());
} } catch (Exception e) {
e.printStackTrace();
} } }
People对象:
package com.test; public class People {
private String id;
private String name;
private String englishName;
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEnglishName() {
return englishName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
} }
xml:
<?xml version="1.0" encoding="UTF-8"?>
<PeopleList>
<People id="1">
<Name en='zhangsan'>张三</Name>
<Age>20</Age>
</People>
<People id="2">
<Name en='lisi'>李四</Name>
<Age>30</Age>
</People>
</PeopleList>