1. 程式人生 > >dom4j使用的小例子

dom4j使用的小例子

int ml2 read sel eval console ati ack val

技術分享

product.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<root>
    <product>
        <index id="1">交換機</index>
        <index id="2">傳送網</index>
        <index id="3">WLAN</index>
        <index id="4">路由器</index>
    </product>
    
    <
scene> <index id="1">規劃</index> <index id="2">實施</index> <index id="3">維護</index> </scene> </root>

代碼:

package com.cy.test;

import java.io.File;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ReadXmlFile { public static void main(String[] args) throws Exception{ String path = URLDecoder.decode(ReadXmlFile.class
.getClassLoader().getResource("").getPath(), "UTF-8") + "product.xml"; SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); //獲取文檔的根節點 Element root = document.getRootElement(); //獲取product的節點 Element element = root.element("product"); List<Element> proList = element.elements(); for(Element e: proList){ String value = e.getTextTrim(); Attribute attr = e.attribute("id"); String key = attr.getValue(); System.out.println("key:" + key + "--value:" +value); } //獲取scene節點 Element sElement = root.element("scene"); List<Element> sList = sElement.elements(); for(Element e : sList){ String value = e.getTextTrim(); String key = e.attributeValue("id"); System.out.println("key:" + key + "----value:" + value); } //將xml轉化為map Map<Integer, String> prodcutMap = xml2Map(path); for (Map.Entry<Integer, String> entry : prodcutMap.entrySet()) { System.out.println("鍵= " + entry.getKey() + " and 值= " + entry.getValue()); } } //將xml轉化為map public static Map<Integer, String> xml2Map(String path) throws Exception{ Map<Integer, String> productMap = new HashMap<Integer, String>(); Document document = new SAXReader().read(path); Element root = document.getRootElement(); //獲取根節點 Iterator<Element> it = root.element("product").elementIterator(); //獲取根節點下的子節點product下面的所有節點 while(it.hasNext()){ Element e = (Element) it.next(); Integer key = Integer.parseInt(e.attributeValue("id")); String value = e.getTextTrim(); productMap.put(key, value); } return productMap; } }

//可以將上面xml2Map改裝,傳入節點名字,nodeName,然後輸出map

console:

技術分享

dom4j使用的小例子