0

I am parsing an XML in Java to check for a certain attribute. The attribute I am searching for is ERG. My code is not working.

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;

public class Parser {

public static void main(String[] args){

  try { 
     File inputFile = new File("parser.txt");
     DocumentBuilderFactory dbFactory 
        = DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     Document doc = dBuilder.parse(inputFile);
     doc.getDocumentElement().normalize();
     System.out.println("Root element :" 
        + doc.getDocumentElement().getNodeName());
     NodeList nList = doc.getElementsByTagName("database");
     for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
           Element eElement = (Element) nNode;
           String nodeAttribute = eElement.getAttribute("key");
           if(nodeAttribute == "ERG"){
               System.out.println("YES");
           }
        }
     }
  } catch (Exception e) {
     e.printStackTrace();

    }
   }
}

Here is my parser.txt

<?xml version="1.0"?>
<databases>
<database key='BC'
   driver='com.micro'
   url.local='456@we'
   login='ses2adm'
   password='12dr'
    />
<database key='SGB'
   driver='com.micro'
   url.local='477@jj'
   login='ses2adm'
   password='12yh'
  />
  <database key='ERG'
   driver='com.micro13'
   url.local='2726@kk'
   login='sdm123'
   password='ghjhj'
  />
  <database key='MESH'
   driver='com.micro'
   url.local='hgh'
   login='adgvnh33'
   password='hghsj'
  />
  <database key='MESJ_EOM'
   driver='com.micro'
   url.local='jujj'
   login='124hh'
   password='sunn'
  />
  <database key='BSUJ'
   driver='com.micro'
   url.local='dkl12'
   login='eh23'
   password='fukll'
  />
  <database key='BSYH_EOM'
   driver='com.micro'
   url.local='skk'
   login='3556'
   password='eyii'
  />
</databases>

1 Answers1

1

You are comparing references to String.

Compare the content of node with String using String.equals() method.

"ERG".equals(nodeAttribute)
Community
  • 1
  • 1
Flowy
  • 420
  • 1
  • 5
  • 15