How to check if xml tag has attributes using SAX Parser in Java?

How to check if xml tag has attributes using SAX Parser in Java?

The startElement method of SaxParser handler has an argument which keeps the list of attributes associated with it. You could rely on that. For example this program prints out all tags with attributes and the attribute names associated with it.

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class FindTagWithAttributes {

    public static void main(String argv[]) {

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                public void startElement(String uri, String localName,
                        String qName, Attributes attributes)
                        throws SAXException {
                    if(attributes != null && attributes.getLength() > 0){
                        System.out.print(qName +  tag has attributes - );
                        for(int i=0; i<attributes.getLength(); i++){
                            System.out.println(attributes.getLocalName(i));
                        }
                    }
                }

                public void endElement(String uri, String localName,
                        String qName) throws SAXException {

                }

                public void characters(char ch[], int start, int length)
                        throws SAXException {

                }

            };

            saxParser.parse(data.xml, handler);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

How to check if xml tag has attributes using SAX Parser in Java?

Leave a Reply

Your email address will not be published. Required fields are marked *