java - How can I use "for" loop and "if" loop both together to verify the existence of xml elements in xml document -
i'm trying make login system. need check existence of xml elements ("username" , "password") in xml document. if match "username" , "password" need return true, otherwise false. use "for" loop go through entire document , use "if" loop validation. i'm using java , dom parser.
xml document:
<login> <user> <username>sunimal</username> <password>1111</password> </user> <user> <username>naveen</username> <password>852</password> </user> <user> <username>chamara</username> <password>12345</password> </user></login>
java code:
boolean = false; try { file inputfile = new file("c:\\users\\kavindu\\documents\\netbeansprojects\\chatserver2\\xml\\userrecord2.xml"); documentbuilderfactory dbfactory = documentbuilderfactory.newinstance(); documentbuilder dbuilder = dbfactory.newdocumentbuilder(); document doc = dbuilder.parse(inputfile); nodelist userlist = doc.getelementsbytagname("login"); (int = 0; < userlist.getlength(); i++) { node user = userlist.item(i); element eelement = (element) user; if (eelement.getelementsbytagname("username").item(i).gettextcontent().equals(username) && eelement.getelementsbytagname("password").item(i).gettextcontent().equals(password)) { = true; } else { = false; } } } catch (exception ex) { } return a; }
if input first elements("sunimal" , "1111"),i can true, other elements return false. tried "for" loop , "if" loop in different ways, couldn't result.i'm newly programming.
here solution; have checked in ide. thanks. :-)
to first element of tag need use index 0. eelement.getelementsbytagname("username").item(0)
when have matched user name , password need out loop,
a = true; break;
otherwise in next iteration set false again.
public boolean checklogin(){ boolean = false; try { file inputfile = new file("c:\\users\\kavindu\\documents\\netbeansprojects\\chatserver2\\xml\\userrecord2.xml"); documentbuilderfactory dbfactory = documentbuilderfactory.newinstance(); documentbuilder dbuilder = dbfactory.newdocumentbuilder(); document doc = dbuilder.parse(inputfile); nodelist userlist = doc.getelementsbytagname("user"); system.out.println("userlist length :: "+ userlist.getlength()); (int = 0; < userlist.getlength(); i++) { node user = userlist.item(i); element eelement = (element) user; if (eelement.getelementsbytagname("username").item(0).gettextcontent().equals(username) && eelement.getelementsbytagname("password").item(0).gettextcontent().equals(password)) { = true; break; } else { = false; } } } catch (exception ex) { system.out.println(ex.getmessage()); } return a; }