package cn.apollo.app.init.data.util.sf;
import java.io.StringReader;
import java.util.HashMap;
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;
import org.xml.sax.InputSource;
/**
*
* @author shenpei
*
*/
public class XmlUtil {
static Map<String, String> xmlMap = new HashMap<String, String>();
/**
* xml字符串轉換成Map
* 獲取標簽內屬性值和text值
* @param xml
* @return
* @throws Exception
*/
public static Map<String, String> xmlToMap(String xml) throws Exception {
StringReader reader=new StringReader(xml);
InputSource source=new InputSource(reader);
SAXReader sax = new SAXReader(); // 創建一個SAXReader對象
Document document=sax.read(source); // 獲取document對象,如果文檔無節點,則會拋出Exception提前結束
Element root = document.getRootElement(); // 獲取根節點
Map<String, String> map = XmlUtil.getNodes(root); // 從根節點開始遍歷所有節點
return map;
}
/**
* 從指定節點開始,遞歸遍歷所有子節點
*
* @author chenleixing
*/
@SuppressWarnings("unchecked")
public static Map<String, String> getNodes(Element node) {
xmlMap.put(node.getName().toLowerCase(),node.getTextTrim());
List<Attribute> listAttr = node.attributes(); // 當前節點的所有屬性的list
for (Attribute attr : listAttr) { // 遍歷當前節點的所有屬性
String name = attr.getName(); // 屬性名稱
String value = attr.getValue(); // 屬性的值
xmlMap.put(name, value.trim());
}
// 遞歸遍歷當前節點所有的子節點
List<Element> listElement = node.elements(); // 所有一級子節點的list
for (Element e : listElement) { // 遍歷所有一級子節點
XmlUtil.getNodes(e); // 遞歸
}
return xmlMap;
}
}