遍历DOM
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.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
public class XmlIterator {
/**
* @param args
*/
public static void main(String[] args) {
interatorXML(new File("person.xml"));
}
/**
* Element类的getContent()方法返回一个List对象
* 它包括了一个元素的所有内容:注释、属性、处理指令、
* 文本和子元素。利用它我们可以遍历XML文档
* @param xmlFile
*/
public static void interatorXML(File xmlFile){
try {
SAXBuilder sax=new SAXBuilder();
Document document=sax.build(xmlFile);
prcess(document.getRootElement());
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void prcess(Element element) {
inspect(element);
List contentList=element.getContent();
Iterator it=contentList.iterator();
while(it.hasNext()){
Object o=it.next();
if (o instanceof Element) {
Element child=(Element)o;
prcess(child);
}else if(o instanceof Comment){
Comment c=(Comment) o;
System.out.println(c.getText());
System.out.println();
}
}
}
private static void inspect(Element element) {
if(!element.isRootElement()){
System.out.println();
}
String qualifiedName=element.getQualifiedName();
System.out.println(element.getName()+":"+element.getText());
Namespace namespace=element.getNamespace();
if (namespace!=Namespace.NO_NAMESPACE) {
String localName=element.getName();
String uri=element.getNamespaceURI();
String prefix=element.getNamespacePrefix();
System.out.println(" Local name: "+localName);
System.out.println(" Namespace URI: "+uri);
if (!"".equals(prefix)) {
System.out.println("NameSpace prefix"+prefix);
}
}
List attList=element.getAttributes();
if (!attList.isEmpty()) {
Iterator it=attList.iterator();
while(it.hasNext()){
Attribute attribute=(Attribute) it.next();
String name=attribute.getName();
String value=attribute.getValue();
Namespace attributeNamespace=attribute.getNamespace();
if (attributeNamespace==Namespace.NO_NAMESPACE) {
System.out.println(" "+name+ "=\""+value+ "\"");
}else {
String prefix=attributeNamespace.getPrefix();
System.out.println(" "+prefix+":"+name+"=\""+value+"\"");
}
}
}
List namespaceList=element.getAdditionalNamespaces();
if (!namespaceList.isEmpty()) {
Iterator iterator=namespaceList.iterator();
while(iterator.hasNext()){
Namespace additional=(Namespace) iterator.next();
String uri=additional.getURI();
String prefix=additional.getPrefix();
System.out.println(" xmlns:"+prefix+"=\""+uri+"\"");
}
}
}
}
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>