使用DOM4J生成解析XML

 到官方下载Dom4j包:http://www.dom4j.org/dom4j-1.6.1/,下载后的DOC内其实已经包含了使用方式

dom4j-1.6.1.jar加到工程内

参考代码:

 

package com.test;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * @说明 DOM4J解析XML
 * @author cuisuqiang
 * @version 1.0
 * @since
 */
@SuppressWarnings("unchecked")
public class Dom4jDemo {
	public static void main(String[] args) {
		String file = "C:\\p.xml"; // 文件存放位置
		Dom4jDemo dj = new Dom4jDemo();
		dj.createXml(file);
		dj.parserXml(file);
	}
	/**
	 * 生成XML
	 * @param filePath 文件路径
	 */
	public void createXml(String filePath) {
		Document document = DocumentHelper.createDocument();
		Element employees = document.addElement("persons");
		Element employee = employees.addElement("person");
		Element name = employee.addElement("name");
		name.setText("java小强");
		Element sex = employee.addElement("sex");
		sex.setText("男");
		Element age = employee.addElement("age");
		age.setText("26");
		try {
			// PrintWriter带有编码格式的构造方法有助于解决乱码问题
			PrintWriter pw = new PrintWriter(filePath, "utf-8");
			XMLWriter xmlWriter = new XMLWriter(pw);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 解析XML
	 * @param filePath 文件路径
	 */
	public void parserXml(String filePath) {
		File inputXml = new File(filePath);
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(inputXml);
			Element root = document.getRootElement();
			for (Iterator persons = root.elementIterator(); persons.hasNext();) {
				Element person = (Element) persons.next();
				for (Iterator pro = person.elementIterator(); pro.hasNext();) {
					Element node = (Element) pro.next();
					System.out.print(node.getName() + ":" + node.getText() + "\t");
				}
				System.out.println();
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

 

请您到ITEYE网站看原创,谢谢!

http://cuisuqiang.iteye.com/ ! 

自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!

你可能感兴趣的:(java,xml,w3c,cuisuqiang,崔素强)