Dom4J解析XML文件


import java.io.*;
import java.util.Iterator;
import java.util.List;

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

import org.dom4j.io.XMLWriter;
import org.dom4j.io.SAXReader;

public class ModelReder {
   
    public static void main(String[] args) {
       
        try {
           
            ModelReder modelReder = new ModelReder();
            modelReder.testWrite();   
            modelReder.testRead();
           
        } catch (Exception e) {
            e.printStackTrace();
        }       
       
    }
   
    public void testRead() throws Exception{
       
        SAXReader reader = new SAXReader();
        Document document = reader.read(new FileInputStream("output.xml"));
       
        Element enterprises = document.getRootElement();
       
        for (Iterator iter = enterprises.elementIterator(); iter.hasNext();) {
            Element enterprise = (Element) iter.next();
            List  enterpriseNames = enterprise.elements();
            for(int i=0; i<enterpriseNames.size(); i++){
                Element enterpriseName = (Element)enterpriseNames.get(i);
                System.out.println(enterpriseName.getText());
               
            }
          
        }
       
    }
    /**
     * 生成XML问津
     * @throws Exception
     */
    public void testWrite() throws Exception{
       
        Document document = DocumentHelper.createDocument();
       
        Element enterprises = document.addElement("enterprises");
        
        for(int i=0; i<10; i++){
        Element enterprise = enterprises.addElement("enterprise");
        Element enterpriseName = enterprise.addElement("enterpriseName").addText("企业名称1");
        Element enterpriseEnglishName = enterprise.addElement("enterpriseName").addText("English Name 1");
         
       
        }
        
        XMLWriter writer = new XMLWriter(new FileOutputStream("output.xml"));
       
        writer.write(document);
        writer.close();   
       
    }
   
}

你可能感兴趣的:(xml)