XML document:
<?xml version="1.0" encoding="GBK"?> <doc> <person id="1" sex="m"> <name>zhangsan</name> <age>32</age> <adds> <add code="home">home add</add> <add code="com">com add</add> </adds> </person> <person id="2" sex="w"> <name>lisi</name> <age>22</age> <adds> <add ID="22" id="23" code="home">home add</add> <add ID="23" id="22" code="com">com add</add> <add id="24" code="com">com add</add> </adds> </person> </doc>
Code traversal:
Public static void main (string [] ARGs) {// todo auto-generated method stubtestparsexmldata ("C:/users/mojia/desktop/dom4j/person. XML ");} public static void testparsexmldata (string xmlfilename) {// todo auto-generated method stubstringbuffer sb = NULL; document = parse2docment (xmlfilename ); element rootelement = document. getrootelement (); sb = new stringbuffer ("------------ start traversing ------------------ \ n"); sb. append (rootelement. getname () + "\ n"); // traverses the child element of the current element for (iterator I _pe = rootelement. elementiterator (); I _pe.hasnext ();) {// obtain the child element e_pe = (element) I _pe.next (); sb. append (e_pe.getname () + "\ t" + e_pe.attributevalue ("ID") + "\ t" + e_pe.attributevalue ("sex") + "\ t "); // obtain the child element name, agestring name = e_pe.element ("name") of person "). gettext (); int age = integer. parseint (e_pe.element ("Age "). gettext (); sb. append ("name ----->" + name + "\ t" + "Age ------>" + age + "\ n"); element e_adds = e_pe.element ("adds "); // traverse the adds element under the current element person for (iterator I _adds = e_adds.elementiterator (); I _adds.hasnext ();) {element e_add = (element) I _adds.next (); string code = e_add.attributevalue ("Code"); string add = e_add.gettexttrim (); sb. append ("\ t" + e_add.getname () + ": "+" code = "+ code +" value = \ "" + Add + "\" \ n ");} sb. append ("\ n");} sb. append ("-------- end --------------"); system. out. println (sb. tostring ();} public static document parse2docment (string xmlfilepath) {saxreader reader = new saxreader (); document = NULL; file F = NULL; try {f = new file (xmlfilepath); inputstream in = new fileinputstream (f); document = reader. read (in);} catch (incluentexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (filenotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} return document ;}