Java解析XML的四种方法--DOM4j

优点: 提供了比JDOM大得多的灵活性,比JDOM更少强调防止不正确的应用程序行为

缺点: 可移植性不强。


import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DOM4j {

	public static void main(String[] args) {
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(new File("books.xml"));
			Element root = doc.getRootElement();
			List ch_list = root.elements();
			System.out.println(root.getName() + "有" + ch_list.size() + "本书\n");
			
			for(Iterator it=root.elementIterator();it.hasNext();) {
				Element ch = (Element)it.next();
				List<Attribute> attr_list = ch.attributes();
				//属性遍历
				for(Attribute attr:attr_list) {
					System.out.println(ch.getName() + "的属性: " + attr.getName() + " = " + attr.getValue());
				}

				for(Iterator itt=ch.elementIterator(); itt.hasNext();) {
					Element ele = (Element)itt.next();
					System.out.println(ele.getName() + ":  " + ele.getText().trim());
				}
				System.out.println("\n---------------");
			}
			
			
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


你可能感兴趣的:(java,xml)