少年阿宾

那些青春的岁月

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

//生成xml文件
package lc.abin.lee.xml.dom4j;

import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class CreateDom4j {
 public static String createXml() throws Exception{
  Document document=DocumentHelper.createDocument();
  Element root=document.addElement("lee");
  Element country=root.addElement("abin");
  Element area=country.addElement("name");
  Element first=area.addElement("lc1");
  first.addText("lc1name");
  Element middle=area.addElement("lc2");
  middle.addText("lc2name");
  Element last=area.addElement("lc3");
  last.addText("lc3name");
  
  FileWriter fileWriter=new FileWriter("lbin.xml");
  OutputFormat format=new OutputFormat();
  format.setEncoding("UTF-8");
  XMLWriter writer=new XMLWriter(fileWriter, format);
  writer.write(document);
  writer.flush();
  writer.close();
  return document.asXML();
 }
 public static void main(String[] args)throws Exception {
  String result=createXml();
  System.out.println("result="+result);
 }
}

生成的XML文件内容
<?xml version="1.0" encoding="UTF-8"?>
<lee><abin><name><lc1>lc1name</lc1><lc2>lc2name</lc2><lc3>lc3name</lc3></name></abin></lee>





//DOM4J解析XML文件

package lc.abin.lee.xml.dom4j;

import java.io.File;
import java.util.Collections;
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 ParseJdom {
 public static Map<String,String> parse(File file) throws DocumentException{
  Map<String,String> map=Collections.synchronizedMap(new HashMap<String,String>());
  SAXReader sax=new SAXReader();
  Document doc=sax.read(file);
  List list=doc.selectNodes("/lee/abin/name");
  for(Iterator it=list.iterator();it.hasNext();){
   Element ele=(Element)it.next();
   for(Iterator its=ele.elementIterator();its.hasNext();){
    Element le=(Element)its.next();
    map.put(le.getName(), le.getText());
    System.out.println("le.getName()="+le.getName());
    System.out.println("le.getText()="+le.getText());
   }
   
  }
  return map;
 }
 public static void main(String[] args) throws Exception {
  File file=new File("lbin.xml");
  Map<String,String> map=parse(file);
  for(Iterator it=map.entrySet().iterator();it.hasNext();){
   Map.Entry entry=(Map.Entry)it.next();
   System.out.println("name="+entry.getKey());
   System.out.println("value="+entry.getValue());
   
  }
 }

}

 

posted on 2012-10-20 21:01 abin 阅读(525) 评论(0)  编辑  收藏 所属分类: dom4j

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


网站导航: