Xml字串dom4j解析
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.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class Dom4j
{
public static Map<String, String> readStringXml(String xml)
{
Document doc = null;
try
{
// 讀取並解析XML文件
// SAXReader就是一個管道,用一個流的方式,把xml檔案讀出來
//
// SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文件
// Document document = reader.read(new File("User.hbm.xml"));
// 下面的是通過解析xml字串的
doc = DocumentHelper.parseText(xml); // 將字串轉為XML
Element rootElt = doc.getRootElement(); // 獲取根節點
System.out.println("根節點:" + rootElt.getName()); // 拿到根節點的名稱
List<Map<String, String>> list = new ArrayList<>();
recursiveNode(rootElt, list);
List<Map<String, String>> resultList = list;
Map<String, String> retMap = new HashMap<>();
for (int i = 0; i < resultList.size(); i++)
{
Map map = resultList.get(i);
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();)
{
String key = (String)iterator.next();
retMap.put(key, (String)map.get(key));
}
}
System.out.println("reMap" + retMap);
return retMap;
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 遞迴遍歷所有的節點獲得對應的值
*
* @param
*/
private static void recursiveNode(Element root, List<Map<String, String>> list)
{
// 遍歷根結點的所有孩子節點
HashMap<String, String> map = new HashMap<>();
for (Iterator iter = root.elementIterator(); iter.hasNext();)
{
Element element = (Element)iter.next();
if (element == null)
{
continue;
}
// 獲取屬性和它的值
for (Iterator attrs = element.attributeIterator(); attrs.hasNext();)
{
Attribute attr = (Attribute)attrs.next();
System.out.println(attr);
if (attr == null)
{
continue;
}
String attrName = attr.getName();
System.out.println("attrname" + attrName);
String attrValue = attr.getValue();
map.put(attrName, attrValue);
}
//如果該節點含有文字資料,也就是葉節點
// 如果有PCDATA,則直接提出
if (element.isTextOnly())
{
String innerName = element.getName();
String innerValue = element.getText();
map.put(innerName, innerValue);
list.add(map);
}
else
{
// 遞迴呼叫
recursiveNode(element, list);
}
}
}
}