xml解析之dom4j

dom4j的api比較簡單,一個demo如下

public class Dom4jParser {

    public static void main(String[] args) throws DocumentException {

		
		//關鍵是用SAXReader 讀取一個資源,返回一個Document
		//然後獲取根節點,剩餘的操作都是基於這個根節點
        InputStream inputSteam = Dom4jParser.class.getClassLoader().getResourceAsStream("group.xml");
        //Resource
        SAXReader reader = new SAXReader();
        Document document = inputSteam .read(file);
        Element element = document.getRootElement();
        getNodes(element);
    }

	//遍歷打印
    private static void getNodes(Element node) {
        System.out.println("--------------------");

        System.out.printf("名稱" + node.getName());
        System.out.printf("內容" + node.getTextTrim());

        List<Attribute> attributes = node.attributes();
        for(Attribute attribute: attributes) {
            String name = attribute.getName();
            String value = attribute.getValue();
            System.out.printf("屬性" + name + ":" + value);
        }

//        List<Element> childs = node.elements();
//        for(Element element: childs) {
//            getNodes(element);
//        }

        Iterator<Element> iterator = node.elementIterator();
        while (iterator.hasNext()) {
            getNodes(iterator.next());
        }

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章