Here, we mainly analyze the Level 3 commonly used. More levels can be written to death, and a layer-by-layer accumulation can also be written to a flexible method to judge whether the level is being parsed. This example is suitable for new people.
Parsed XML:
<? XML version = "1.0" encoding = "GBK"?> <Rowdata> <row> <A> 1111 </a> <B> 2222 </B> <C> 3333 </C> <D> 4444 </D> </ row> <row> <A> AAAA </a> <B> BBBB </B> <C> CCCC </C> <D> dddd </D> </row> </rowdata>
Pasexml class:
Package com.cn; import Java. util. arraylist; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import Org. dom4j. document; import Org. dom4j. extends entexception; import Org. dom4j. element; import Org. dom4j. io. saxreader;/*** parse third-level XML **/public class pasexml {public list <Map <string, string> pxml (string filename) {Map <string, string> map = NULL; List <Map <string, strin G> List = new arraylist <Map <string, string> (); saxreader reader = new saxreader (); try {document = reader. read (filename); element root = document. getrootelement (); iterator <?> It = root. elementiterator (); While (it. hasnext () {map = new hashmap <string, string> (); // row node Element E = (element) it. next (); iterator <?> Its = E. elementiterator (); While (its. hasnext () {element El = (element) its. next (); // put the key value of XML into map. put (El. getname (), El. gettext ();} List. add (MAP) ;}} catch (incluentexception E1) {e1.printstacktrace ();} return list ;}}
Main class:
Public static void main (string [] ARGs) {pasexml PX = new pasexml (); string filename = "D:/xmlfile/test. XML "; // string filename =" D:/xmlfile/hospital. XML "; List <Map <string, string> List = px. pxml (filename); iterator <?> It = List. iterator (); While (it. hasnext () {Map <string, string> map = (Map <string, string>) it. next (); iterator <?> ITM = map. entryset (). iterator (); While (ITM. hasnext () {map. entry entry = (map. entry) ITM. next (); object key = entry. getkey (); object value = entry. getvalue (); system. out. println (Key + ":" + value);} system. out. println ("----------------------------------");}}
Output result:
D: 4444
B: 2222
C: 3333
A: 1111
----------------------------------
D: dddd
B: BBBB
C: CCCC
A: AAAA
----------------------------------