XML parsing in java [closed]
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 DefaultHandler
class provides a callback to listen for start elements, and it has a signature that contains an Attributes
object, representing the attributes of that element.
startElement(String uri, String localName, String qName, Attributes attributes)
Looking at the Attributes
interface, I see methods to help you out.
- If you don't know which attributes you are interested in, and you want to look at all attributes, you should use
getLength()
, and the do afor-loop
over 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). - If you do know which attributes you are interested in, you can simply call
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:
public void startElement(String ns, String localName, String qName, Attributes attrs) throws SAXException {
for(int i = 0; i < attrs.getLength(); ++i) {
String attrName = attrs.getLocalName(i);
String attrValue = attrs.getValue(i);
//do stuff with name/value
}
}
SAX programming can be very confusing if you're not used to it. Constructing the parser is a bit tricky because you have to struggle with the abstract Interface API. Once you get it all going and register your handler though, accessing the attributes should be straightforward; your handler class need to implement the method:
public void startElement(String nsUri, String localName, String qName, Attributes attributes)
throws SAXException
The attribute values are available in the arg of that name.
精彩评论