---
title: "How to read xml use JDOM in java application"
author: "cainwise"
date: "2009-04-01T17:52:17Z"
tags: []
slug: "how-to-read-xml-use-jdom-in-java-application"
draft: false
lastmod: "2009-04-01T17:52:17Z"
id: 359262
url: "https://cainwise.iteye.com/blog/359262"
---

刚才写了一篇create xml文件用JDOM来生成，那么下面我来说说如何取出里面的内容

我只是做个事例，其他的都差不多！！

代码如下

```
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


public class ReadXML {
	public static void main(String[] args) {
		readxml();
	}
	private static void readxml() {
		SAXBuilder sb=new SAXBuilder();
		Document doc = null;
		try {
			doc=sb.build(new FileInputStream("lib/users.xml"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element root=doc.getRootElement();
		System.out.println(root.getName());
		List children=root.getChildren();
		int i=1;
		elements(children,i);
	}
	private static void elements(List children,int i) {
		Iterator itr = children.iterator();
		String lo="";
		for(int j=0;j<i;j++){
			lo+="==";
		}
		boolean hasnext = false;
		if(hasnext=itr.hasNext()){
			while(itr.hasNext()){
				Element el = (Element)itr.next();
				System.out.println(lo+el.getName());
				if(el.getChildren()!=null){
					Iterator itr1 = el.getChildren().iterator();
					elements(el.getChildren(),i+1);
				}
			}
		}
	}

}
```