java - how to parse some specific nodes of xml using sax or dom based on given condition -
i new jaxp , stuck have parse xml using either sax or dom. have ask user enter empoyee code , display other nodes of particular employee for ex:if user enters 101 show
ename:akshay ecode:101 dp no.:10 mgr code=201
i tried alot no results,can help.
<employees> <employee> <ename>akshay</ename> <ecode>101</ecode> <empsal>2100.0</empsal> <department_code>10</department_code> <manager_code>201</manager_code> </employee> <employee> <ename>rahul</ename> <ecode>102</ecode> <empsal>21000.0</empsal> <department_code>20</department_code> <manager_code>202</manager_code> </employee> </employees>
the code tried parse xml
public class parseusingdom { public static void main(string[] args) { try { documentbuilderfactory factory = documentbuilderfactory .newinstance(); documentbuilder builder = factory.newdocumentbuilder(); document document = builder.parse("emp.xml"); nodelist list = document.getelementsbytagname("*"); int count = 0; { (int = 0; < list.getlength(); i++) { element element = (element) list.item(i); string nodename = element.getnodename(); if (nodename.equals("employee")) { count++; system.out.println("employee :" + count); } else if (nodename.equals("ename")) { system.out.println("\tename:\t" + element.getchildnodes().item(0).getnodevalue()); } else if (nodename.equals("ecode")) { system.out.println("\tecode:\t" + element.getchildnodes().item(0).getnodevalue()); } else if (nodename.equals("empsal")) { system.out.println("\tempsal:\t" + element.getchildnodes().item(0).getnodevalue()); } else if (nodename.equals("department_code")) { system.out.println("\tdepartment_code: " + element.getchildnodes().item(0).getnodevalue()); } else if (nodename.equals("manager_code")) { system.out.println("\tmanager code:\t" + element.getchildnodes().item(0).getnodevalue()); } } }} catch (parserconfigurationexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (saxexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
}
this pretty straight forward.
- parse xml
document
documentbuilder
. - ask user id. if command line,
scanner
might help. - select relevant data document.
xpath
start.
take these steps individually , figure out how them. put , you've got solution.
Comments
Post a Comment