Using SAX parser in Java, how to do attribute based parsing.
Suppose my xml file is as follows,
<?xml version="1.0" encoding="UTF-8"?>
<employees category="1" type="regular" location="india">
<employee name="xyz" doj="20/12/2001" dob="21/12/1988" salary="12000"></employee>
<employee name="xyz" doj="22/12/2003" dob="22/12/1988" salary="18000"></employee>
<employee name="xyz" doj="23/12/2002" dob="23/12/1988" salary="15000"></employee>
<employee name="xyz" doj="24/12/2003" dob="22/12/1988" salary="17000"></employee>
<employee name="xyz" doj="26/12/2005" dob="24/12/1988" salary="12000"></employee>
</employees>
I want to fetch the each attribute values of employee element. Please help me out
The
DefaultHandlerclass provides a callback to listen for start elements, and it has a signature that contains anAttributesobject, representing the attributes of that element.startElement(String uri, String localName, String qName, Attributes attributes)Looking at the
Attributesinterface, I see methods to help you out.getLength(), and the do afor-loopover that length, looking at each attributesgetLocalName(int)orgetQName(int), and you can find its value by callinggetValue(int)(allint‘s are used as indices into the attributes list).getValue(String), passing in the string name of the attribute you are after.Here is some example code that could get you the names and values of all attributes of a given element: