解析xml文件

package com.ss1.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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


public class Dom4jTest {
    
    public static void main(String[] args) throws IOException, DocumentException {

        /*Document document = DocumentHelper.createDocument();
        
        Element root = DocumentHelper.createElement("student");
        
        document.setRootElement(root);
        
        root.addAttribute("name", "zhangsan");
        Element helloElement = root.addElement("hello");
        
        Element worldElement = root.addElement("world");
        helloElement.setText("hello text");
        worldElement.setText("world text");
        
        XMLWriter xmlWriter = new XMLWriter();
        xmlWriter.write(document);
        /ss1/src/students.xml
    
        OutputFormat format = new OutputFormat("    ",true);
        XMLWriter xmlWriter2 = new XMLWriter(new FileOutputStream("student.xml"),format);
        xmlWriter2.write(document);
        */
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File("test.xml"));
        
        Element rootElement = document.getRootElement();
        System.out.println(rootElement);
        
        
    }

}
package com.ss1.xml;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jXml {

    public static void main(String[] args) throws DocumentException {
        File file = new File("test.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(file);
        
        Element rootElement = document.getRootElement();
        for(Iterator iterator = rootElement.elementIterator("students");iterator.hasNext();){
            Element element = (Element) iterator.next();
            Attribute nameAttribute = element.attribute("name");
            String name = nameAttribute.getValue();
            Attribute idAttribute = element.attribute("id");
            String id = idAttribute.getValue();
            System.out.println(name);
            System.out.println(id);
            
        }
    }
}

 

posted @ 2016-08-19 09:13  公众号java-codestack  阅读(294)  评论(0编辑  收藏  举报