您的位置:首页 > 编程语言 > Java开发

java递归遍历Xml

2015-04-27 15:30 337 查看
import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class XMLDocParser {

private HashMap<String,XmlElement> map = new HashMap<String,XmlElement>();

public XMLDocParser()

{

}

/**

*

* @param xmlContent

* @param r

* @throws UnsupportedEncodingException

*/

public void parseXml(String xmlContent ) throws UnsupportedEncodingException

{

SAXReader reader = new SAXReader();

Document doc;

java.io.BufferedInputStream is =null;

try

{

is = new java.io.BufferedInputStream(new java.io.ByteArrayInputStream(xmlContent.getBytes("UTF-8")));

doc = reader.read(is);

Element root = doc.getRootElement();

Iterator<Element> allSons = root.elementIterator();

while(allSons.hasNext()){

getLeafNodes(allSons.next());

}

for(String key:map.keySet()){

System.out.println(map.get(key).getTagName());

}

}

catch (DocumentException e)

{

e.printStackTrace();

}finally{

try {

if(is!=null){

is.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

// r.setElementMap(map);

}

/**

* 获取叶子节点

* @param currentNode

* @return

*/

private void getLeafNodes(Element currentNode)

{

Element e = currentNode;

String elementTag = e.getName();

String elementValue = e.getStringValue();

String elementParmentTag = e.getParent().getName();

XmlElement xmle = new XmlElement(elementTag, elementValue, elementParmentTag);

map.put(elementTag,xmle);

if ((e.elements()).size() >= 0)

{

List<Element> el = e.elements();

for (Element sonNode : el)

{

getLeafNodes(sonNode);

}

}

}

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

String xml="<html><head><xx>ooxx</xx></head><body><mm>123</mm><oo>xxx</oo><nn>123456</nn></body></html>";

XMLDocParser a = new XMLDocParser();

a.parseXml(xml);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: