java解析xml,主要是通过Dom4j实现的,很多场合都会用到此功能,需要解析XML文件。
下面是一个简单的解析XML文件的例子:
import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 解析XML文件 * * @author sunlightcs 2011-4-29 * http://hi.juziku.com/sunlightcs/ */ public class XmlUtils { /** * 解析XML文件 * @param path XML文件的路径 */ public static void parserXml(String path){ SAXReader reader = new SAXReader(); try { Document document = reader.read(path); Element root = document.getRootElement(); /** * 遍历XML节点 */ for(Iterator i = root.elementIterator(); i.hasNext();){ Element el = (Element )i.next(); System.out.println("userId:"+el.elementText("userId")); System.out.println("userName:"+el.elementText("userName")); System.out.println("email:"+el.elementText("email")); System.out.println("============================"); } } catch (DocumentException e) { e.printStackTrace(); } } public static void main(String[] args) { parserXml("userList.xml"); } }
XML文件结构如下:
<?xml version="1.0" encoding="UTF-8"?> <user-list> <user> <userId>1</userId> <userName>张三</userName> <email>user1@xxx.com</email> </user> <user> <userId>2</userId> <userName>李四</userName> <email>user2@xxx.com</email> </user> <user> <userId>3</userId> <userName>王五</userName> <email>user3@xxx.com</email> </user> </user-list>
执行的结果如下:
userId:1
userName:张三
email:user1@xxx.com
============================
userId:2
userName:李四
email:user2@xxx.com
============================
userId:3
userName:王五
email:user3@xxx.com
============================
下面是dom4j下载地址:
http://dom4j.sourceforge.net/