Search code examples
javaandroidxmlsax

How to check if XML attribute exists using SAX parser?


I gave an XML file and one tag contains number of attributes. However one of them sometimes gets skipped. Exampe:

<data>
    <item attribute0="value 0" attribute1="value 1" attribute2="value 2">
    <item attribute0="value 0" attribute1="value 1">
    <item attribute0="value 0" attribute1="value 1" attribute2="value 2">
</data>

I am using SAX parser to handle this file and in a startElement method I am getting all the attribute's values but before getting attribute2 I need to check if it exists.


Solution

  • You can check if an attribute exists by using getIndex(name) or getIndex(uri, localName). If it returns -1, then the attribute did not exists. See getIndex javadoc.