here is my code :
public void Login() {
try{
DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = builderfactory.newDocumentBuilder();
File path = new File("src/dataPengguna/dataPengguna.xml");
Document doc = db.parse(path);
Element pengguna = (Element) doc.getElementsByTagName("pengguna");
NodeList list = pengguna.getElementsByTagName("user");
for (int i = 0; i < list.getLength(); i++) {
Element user = (Element) list.item(i);
Node username = user.getElementsByTagName("username").item(i);
Node password = user.getElementsByTagName("password").item(i);
if(loginuser.getText().equals(username.getTextContent())
&& loginpass.getText().equals(password.getTextContent())){
JOptionPane.showMessageDialog(rootPane, "welcome");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
here is my xml :
<?xml version="1.0" encoding="UTF-8"?>
<pengguna>
<user>
<nama>septian</nama>
<username>septiansykes</username>
<password>1234</password>
<status>belumpinjam</status>
</user>
<user>
<nama>koko</nama>
<username>kokosan</username>
<password>12er</password>
<status>belumpinjam</status>
</user>
<user>
<nama>tamrin</nama>
<username>tamrincs</username>
<password>gt234</password>
<status>belumpinjam</status>
</user>
</pengguna>
and here is my error :
java.lang.ClassCastException:com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Element
i try to get the element at the xml file, i want to check the element username and password, but there is an error about the cast class, it's seem difficult for me,... thanks before
This is the problem:
Element pengguna = (Element) doc.getElementsByTagName("pengguna");
getElementsByTagName
doesn't return a single element - it returns multiple elements. You probably want something like:
NodeList penggunas = doc.getElementsByTagName("pengguna");
if (penggunas.getLength() != 1) {
// Handle this - e.g. throw an exception
}
Element pengguna = (Element) penggunas.item(0);
EDIT: Later, you've got a bug here:
Node username = user.getElementsByTagName("username").item(i);
Node password = user.getElementsByTagName("password").item(i);
This should be:
Node username = user.getElementsByTagName("username").item(0);
Node password = user.getElementsByTagName("password").item(0);
You're already within the user
element - so you always want the first username
and password
elements within that element. Otherwise you're asking for the second username
element within the second user
element, the third username
element within the third user
element etc. The numbering is relevant to the element that you're in, not some global count.