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);
}
}