package com.liuc.test;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class JdomTest {
/**
* @param args
*/
public static void main(String[] args) {
praseXML(new File("person.xml"));
}
/**
* 解析XML方法
*/
public static void praseXML(File xmlFile){
SAXBuilder sax=new SAXBuilder(); //在内存中建立一个SAX文档模型
try {
//创建文档
Document xmlDom=sax.build(xmlFile);
//获得文档的根元素
Element root=xmlDom.getRootElement();
System.out.println("根元素是"+root);
//获得根元素的子节点
List childList=root.getChildren();
Iterator it=childList.iterator();
while(it.hasNext()){
Element element=(Element) it.next();
System.out.println("孩子节点是"+element.getName());
}
//获得第一个孩子节点
Element firstChild=(Element) childList.get(0);
//获取孩子节点的属性
List attriList=firstChild.getAttributes();
Iterator attrIt=attriList.iterator();
while(attrIt.hasNext()){
Attribute attr = (Attribute )attrIt.next();
System.out.println("第一个元素属性是"+attr.getName());
System.out.println("属性的值是"+attr.getValue());
System.out.println("属性的类型是"+attr.getAttributeType());
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}//创建文档
}
}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person perid="1001">
<name>zhangsan</name>
<age>89</age>
<address>安徽淮北</address>
<sex>男</sex>
</person>
<person perid="1002">
<name>lisi</name>
<age>56</age>
<address>北京海淀</address>
<sex>女</sex>
</person>
</persons>