All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.squeakysand.commons.xml.SaxHelper Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2010-2012 Craig S. Dickson (http://craigsdickson.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.squeakysand.commons.xml;

import com.squeakysand.commons.lang.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Provides convenience methods for parsing XML documents using the SAX framework.
 */
public final class SaxHelper {

    private static final Logger LOG = LoggerFactory.getLogger(SaxHelper.class);

    private SaxHelper() {
    }

    /**
     * Returns a List of all of the content values of a particular element.
     *
     * @param   elementName  DOCUMENT ME!
     * @return  DOCUMENT ME!
     */
    public static List getValues(URL xmlUrl, final String elementName) throws XmlProcessingException {
        final List result = new ArrayList();
        ContentHandler contentHandler = new DefaultHandler() {

            private boolean isElement;

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (isElement) {
                    result.add(String.valueOf(ch, start, length));
                }
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (localName.equals(elementName)) {
                    isElement = false;
                }
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (localName.equals(elementName)) {
                    isElement = true;
                }
            }

        };
        parse(xmlUrl, contentHandler, null);
        return result;
    }

    /**
     * Parses the specified XML and returns a list of all of the values of the specified attribute of any elements with
     * the specified element name. If the elementName is null, then returns the values of the specified attributeName on
     * all elements.
     */
    public static List getValues(URL xmlUrl, final String elementName, final String attributeName) throws XmlProcessingException {
        final List result = new ArrayList();
        ContentHandler contentHandler = new DefaultHandler() {

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (StringUtils.isNullOrEmpty(elementName) || localName.equals(elementName)) {
                    if (attributes != null) {
                        for (int i = 0; i < attributes.getLength(); i++) {
                            String currentAttributeName = attributes.getLocalName(i);
                            if (currentAttributeName.equals(attributeName)) {
                                String attributeValue = attributes.getValue(i);
                                result.add(attributeValue);
                            }
                        }
                    }
                }
            }

        };
        parse(xmlUrl, contentHandler, null);
        return result;
    }

    /**
     * Convenience method that takes care of the SAX scaffolding code and allows the client to just write the
     * contentHandler code.
     *
     * @param   contentHandler  standard SAX contentHandler for content events.
     * @param   errorHandler    standard SAX contentHandler for error events, can be null.
     */
    public static void parse(URL xmlUrl, ContentHandler contentHandler, ErrorHandler errorHandler) throws XmlProcessingException {
        InputStream inputStream = null;
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            SAXParser saxParser = spf.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            xmlReader.setContentHandler(contentHandler);
            xmlReader.setErrorHandler(errorHandler);
            inputStream = xmlUrl.openStream();
            InputSource source = new InputSource(inputStream);
            xmlReader.parse(source);
        } catch (ParserConfigurationException e) {
            throw new XmlProcessingException(e);
        } catch (IOException e) {
            throw new XmlProcessingException(e);
        } catch (SAXException e) {
            throw new XmlProcessingException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOG.warn(e.getMessage(), e);
                }
            }
        }

    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy