关闭

dom4j解析XML文档案例

标签: java解析XML的四种方法
190人阅读 评论(1) 收藏 举报
分类:
package com.ju.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

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

/**
 * dom4j解析xml
 * @author fc
 *
 */
public class Dom4jDemo {
	
	public void createXml(String fileName) {   
		Document document = DocumentHelper.createDocument();   
		Element employees=document.addElement("employees");   
		Element employee=employees.addElement("employee");   
		Element name= employee.addElement("name");   
		name.setText("ddvip");   
		Element sex=employee.addElement("sex");   
		sex.setText("m");   
		Element age=employee.addElement("age");   
		age.setText("29");   
		try {   
		Writer fileWriter=new FileWriter(fileName);   
		XMLWriter xmlWriter=new XMLWriter(fileWriter);   
		xmlWriter.write(document);   
		xmlWriter.close();   
		} catch (IOException e) {   

		System.out.println(e.getMessage());   
		}   

		}   
	
	public void parseXml(String fileName){
		File xmlFile = new File(fileName);
		SAXReader saxReader = new SAXReader();   
		try {
			Document document = saxReader.read(xmlFile);
			Element employees = document.getRootElement();
			for(Iterator i = employees.elementIterator(); i.hasNext();){     
				Element employee = (Element) i.next();     
				for(Iterator j = employee.elementIterator(); j.hasNext();){     
				Element node=(Element) j.next();     
				System.out.println(node.getName()+":"+node.getText());     
				}     
			}   
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
public static void main(String[] args) {
	Dom4jDemo demo = new Dom4jDemo();
	demo.parseXml("d:\\b.xml");
}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:400次
    • 积分:17
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    文章存档