少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

package com.abin.lee.dom4j;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class CreateDom4j {
 public static String createXml(){
  Document document=DocumentHelper.createDocument();
  Element school=document.addElement("school");
  Element teacher=school.addElement("teacher");
  Element student=teacher.addElement("student");
  student.addText("abin");
  Element boy=teacher.addElement("boy");
  boy.addText("han");
  Element girl=teacher.addElement("girl");
  girl.addText("xia");
  
  return document.asXML();
 }
 
 public static Map<String, String> parseXml(String xml){
  Map<String, String> map=new HashMap<String, String>();
  Document doc=null;
  try {
   doc=DocumentHelper.parseText(xml);
   Element school=doc.getRootElement();
   System.out.println("school Name="+school.getName());
   System.out.println("school Value="+school.getText());
   map.put(school.getName(), school.getText());
   
   Element teacher=school.element("teacher");
   map.put(teacher.getName(), teacher.getText());
   
   Element student=teacher.element("student");
   map.put(student.getName(), student.getText());
   
   Element boy=teacher.element("boy");
   map.put(boy.getName(), boy.getText());
   
   Element girl=teacher.element("girl");
   map.put(girl.getName(), girl.getText());
  } catch (Exception e) {
   e.printStackTrace();
  }
  return map;
 }
 
 public static Map<String, String> parseString(String xml){
  Map<String, String> map=new HashMap<String, String>();
  Document doc=null;
  try {
   doc=DocumentHelper.parseText(xml);
   Element school=doc.getRootElement();
   map.put(school.getName(), school.getText());
   
   Element teacher=school.element("teacher");
   map.put(teacher.getName(), teacher.getText());
   
   for(Iterator it=teacher.elementIterator();it.hasNext();){
    Element element=(Element)it.next();
    map.put(element.getName(), element.getText());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return map;
 }
 public static void main(String[] args) {
  String result=createXml();
  System.out.println("result="+result);
//  Map<String, String> map=parseXml(result);
//  for(Iterator it=map.entrySet().iterator();it.hasNext();){
//   Map.Entry entry=(Map.Entry)it.next();
//   System.out.println("entry name="+entry.getKey());
//   System.out.println("entry value="+entry.getValue());
//  }
  
  Map<String, String> map=parseString(result);
  for(Iterator it=map.entrySet().iterator();it.hasNext();){
   Map.Entry entry=(Map.Entry)it.next();
   System.out.println("entry name="+entry.getKey());
   System.out.println("entry value="+entry.getValue());
  }
  
  
 }

}


http://hi.baidu.com/stevenjohn/item/aababd47077c0ce5dd0f6c78

posted on 2012-08-29 22:45 abin 阅读(682) 评论(0)  编辑  收藏 所属分类: dom4j

只有注册用户登录后才能发表评论。


网站导航: