Dom4J 解析案例

 

public class Analisys { 


public static void main(String[] args) throws Exception { 
File file = new File( 
"E:\\MyEclipse 6.5\\newworkspace\\test\\src\\test\\java\\com\\supporter\\xml\\data.xml"); 
System.out.println("begin analysis file:" + file.getName()); 
analisys(file); 
} 

private static void analisys(File file) throws Exception { 
SAXReader saxReader = new SAXReader(); 
Document document = saxReader.read(file); 

Element rootElm = document.getRootElement(); 

List<Person> list = new ArrayList<Person>(); 
recurveCall(rootElm, list); 
for (Iterator<Person> it = list.iterator(); it.hasNext();) { 
System.out.println(it.next() + "\n"); 
} 
} 

private static void recurveCall(Element root, List<Person> list) { 
Iterator<Element> it = root.elementIterator(); 
Person p = null; 
int i = 1; 
for (; it.hasNext(); i++) { 
Element e = it.next(); 
String eleName = e.getName(); 
String layer = eleName.substring(5, eleName.length()); 
int reallayer = Integer.valueOf(layer); 
System.out.println("layer is :" + reallayer); 
p = new Person(e.attributeValue("name"), e.attributeValue("age"), 
(reallayer + 1) * 100 + i); 
list.add(p); 
recurveCall(e, list); 
} 
} 
} 


上例对应的xml: 
<datas> 
<level0 name="yang0" age="0"> 
<level1 name="yang1" age="1"> 
<level2 name="yang2" age="2"></level2> 
</level1> 
<level1 name="yang01" age="3"> 
<level2 name="yang11" age="4"></level2> 
<level2 name="yang12" age="5"></level2> 
</level1> 
</level0> 

<level0 name="ding" age="00"> 
<level1 name="ding1" age="01"> 
<level2 name="ding2" age="02"></level2> 
</level1> 
<level1 name="ding01" age="03"> 
<level2 name="ding11" age="04"></level2> 
<level2 name="ding12" age="05"></level2> 
</level1> 
</level0> 
</datas>

你可能感兴趣的:(xml,MyEclipse)