I have .xml
files inside a package in my Java project that contains data in the following format...
<?xml version="1.0"?>
<postcodes>
<entry postcode='AB1 0AA' latitude='7.101478' longitude='2.242852' />
</postcodes>
I currently have overrided the startElement()
in my custom DefaultHandler
to the following;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (attributes.getValue("postcode") == "AB43 8TZ"){
System.out.println("The postcode 'AB43 8TZ', has a latitude of "+attributes.getValue("latitude")+" and a longitude of "+attributes.getValue("longitude"));
}
}
I know the code is working outside of this method because I previously tested it by having it print out all of the attributes for each element and that worked fine. Now however, it does nothing, as if it never found that postcode value. (I know it's there because it's a copy paste job from the XML source)
Extra details; Apologies for originally leaving out important details. Some of these files have up to 50k lines, so storing them in memory is a no no if at all possible. As such, I am using SAX. As a side, I use the words "from these files from within my project" because I also can't find how to reference a file from within the same project rather than from an absolute directory.
(From comments as requested by OP.)
First, you cannot compare strings with the ==
operator. Use equals()
instead. See the question How do I compare strings in Java? for more information.
Second, not every element has the postcode attribute, so it is possible that you will be invoking equals()
on a null
object, leading to NullPointerException
. Do it the other way around, e.g.
"AB43 8TZ".equals(attributes.getValue("postcode"))