Domj 访问XML 简单小例子

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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


public class WriteRoFiel {


    public Map testRead() throws Exception{
       
        SAXReader reader = new SAXReader();
        Document document = reader.read(new FileInputStream("output.xml"));
        Map map = new HashMap();
       
        Element root = document.getRootElement();
       
        for (Iterator iter = root.elementIterator(); iter.hasNext();) {
            Element element = (Element) iter.next();
            String enterprieeName = element.getText();
            String startNo = element.attributeValue("start").toString();
            map.put("enterprieeName", enterprieeName);
            map.put("startNo", startNo);
        }
        return map;
    }
   
    public void testWrite(String enterprieeName, String startNo) throws Exception{
       
        Document document = DocumentHelper.createDocument();
       
        Element root = document.addElement("root");
        Element element1 = root.addElement("user")
        .addAttribute("start", startNo)
        .addText(enterprieeName);

       
        XMLWriter writer = new XMLWriter(new FileOutputStream("output.xml"));
       
        writer.write(document);
        writer.close();   
       
    }
 

}

你可能感兴趣的:(java,xml)