sakura
sakura

Reputation: 309

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

I would like to ask you a problem regarding to xml file. I want to check if xml tag has attributes or not by using SAX Parser in Java.

Any answers? Please help me...

Upvotes: 2

Views: 1724

Answers (1)

Syam S
Syam S

Reputation: 8509

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();
        }

    }

}

Upvotes: 2

Related Questions