/**
* RecursiveWholeXMLUtil.java
* com.hao947.XMLUtil
*
* Function: TODO
*
* ver date author
* ──────────────────────────────────
* 2014-2-5 雪藏的心
*
* Copyright (c) 2014, inspurworld All Rights Reserved.
*/
package com.hao947.XMLUtil;
import java.io.File;
import java.util.ArrayList;
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.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
/**
* ClassName:RecursiveWholeXMLUtil
* Function: TODO ADD FUNCTION
* Reason: TODO ADD REASON
*
* @author 雪藏的心
* @version
* @since Ver 1.1
* @Date 2014-2-5 下午3:34:06
*
* @see
* @deprecated
*/
public class RecursiveWholeXMLUtil {
public static List<Map<String, String>> RecursiveWholeXML(String filename) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File(filename));
Element root = document.getRootElement();
// 递归
recursiveNode(root, list);
return list;
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* recursive Node:(递归遍历所有的节点获得对应的值)
*
* @param @param root
* @param @param list 设定文件
* @return void DOM对象
* @throws
* @since CodingExample Ver 1.1
*/
private static void recursiveNode(Element root ,
List<Map<String, String>> list) {
// 遍历根节点的所有孩子节点
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
HashMap<String, String> map = new HashMap<String, String>();
Element element = (Element) iter.next();
if (element == null)
continue;
// 获取属性和它的值
for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {
Attribute attr = (Attribute) attrs.next();
if (attr == null)
continue;
String attrName = attr.getName();
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 {
list.add(map);
// 递归调用
recursiveNode(element, list);
}
}
}
@Test
public void show() {
String filename = "src\\users.xml";
List<Map<String, String>> list = RecursiveWholeXMLUtil
.RecursiveWholeXML(filename);
for (Map<String, String> map : list) {
for (String ss : map.keySet()) {
System.out.println(ss + ":" + map.get(ss));
}
}
}
}
java DOM4J 无限连解析XML
最新推荐文章于 2022-11-23 11:24:53 发布