Reputation: 893
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.
Upvotes: 1
Views: 9323
Reputation: 11
My answer builds up on the answer from Javanator, using the SAX Parser.
You can check if the attribute is empty by:
if (item.getAttribute("attribute2").isEmpty()) { }
public boolean isEmpty()
Returns:true if length() is 0, otherwise false
An alternative way to ask if a specific attribute exists is:
if (item.hasAttribute("attribute2")) { }
boolean hasAttribute(String name)
Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.
Upvotes: 1
Reputation: 13825
This link is a good example of SAXParser
http://java-samples.com/showtutorial.php?tutorialid=152
In the startElement delegate we usually go for reading Attributes(org.xml.sax.Attributes)
//Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// Read Attributes Here
}
Firstly you can also look for
attributes.getLength()
method to ensure whether you get your desired number of attributes in the feed or not
What would be really preferable is that you should not be worry about these and code as if you will get all.
If
attributes.getValue("blahblah");
gives null. that means it is not there.
And you fill null directly into your data objects and take precautions in using them in the code itself. (null check etc)
Hope it helps :)
Upvotes: 0
Reputation: 11553
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.
Upvotes: 1