java使用dom4j读取xml的简单例子

例如读取如下一个xml文件

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<user>
		<id>1</id>
		<name>abc</name>
	</user>
	<user>
		<id>2</id>
		<name>xyz</name>
	</user>
</root>

dom4j读取上面xml文件的代码如下:

package com.codeif.test;

import java.util.Iterator;
import org.dom4j.*;
import org.dom4j.io.*;
/**
 * @author codeif.com
 */
public class Dom4jTest {
	public static void main(String[] args) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read("test.xml");
		Element root = doc.getRootElement();
		Element foo;
		for (Iterator i = root.elementIterator("user"); i.hasNext();) {
			foo = (Element) i.next();
			System.out.print("ID:" + foo.elementText("id"));
			System.out.println(" Name:" + foo.elementText("name"));
		}
	}
}

你可能感兴趣的:(java,xml,String,iterator,import,encoding)