Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:MyContentHandler.java

static public void main(String[] arg) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader reader = null;
    try {/*from  w ww  . j a  v  a2  s.c  o  m*/
        SAXParser parser = spf.newSAXParser();
        reader = parser.getXMLReader();
    } catch (Exception e) {
        System.err.println(e);
        System.exit(1);
    }

    reader.setErrorHandler(new MyErrorHandler());
    reader.setContentHandler(new MyContentHandler());

    try {
        InputSource is = new InputSource("test.xml");
        reader.parse(is);
    } catch (SAXException e) {
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e);
        System.exit(1);
    }
}

From source file:SAXCopy.java

static public void main(String[] arg) {
    String infilename = null;// ww  w.ja v  a 2s.c  o m
    String outfilename = null;
    if (arg.length == 2) {
        infilename = arg[0];
        outfilename = arg[1];
    } else {
        usage();
    }

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new MyErrorHandler());
        FileOutputStream fos = new FileOutputStream(outfilename);
        PrintWriter out = new PrintWriter(fos);
        MyCopyHandler duper = new MyCopyHandler(out);
        reader.setContentHandler(duper);
        InputSource is = new InputSource(infilename);
        reader.parse(is);
        out.close();
    } catch (SAXException e) {
        System.exit(1);
    } catch (ParserConfigurationException e) {
        System.err.println(e);
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e);
        System.exit(1);
    }
}

From source file:TypeInfoWriter.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//  www . j av a2 s .co m
        System.exit(1);
    }

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // process arguments
    for (int i = 0; i < argv.length; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    // use default parser?
    if (parser == null) {
        // create parser
        try {
            parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
        } catch (Exception e) {
            System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:Main.java

/**
 * Parse the XML data in the given input stream, using the
 * specified handler object as both the content and error handler.
 *
 * @param handler the SAX event handler//from w  w w .j a v  a  2s . c  om
 * @param in the input stream containing the XML to be parsed
 */
public static void parse(DefaultHandler handler, InputStream in)
        throws IOException, ParserConfigurationException, SAXException {
    XMLReader xr = _pfactory.newSAXParser().getXMLReader();

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);

    xr.parse(new InputSource(in));
}

From source file:Main.java

public static XMLReader parse(InputStream in, ContentHandler handler) throws SAXException, IOException {

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(handler);
    reader.parse(new InputSource(in));
    in.close();/*from   w w  w.  jav  a2s .com*/
    return reader;
}

From source file:Main.java

/**
 * Creates a non-validating, non-namespace-aware {@link XMLReader} using the specified
 * {@link ContentHandler}.//  www  .j a  va 2s  .  com
 *
 * <p>If the given {@link ContentHandler} is <code>null</code>, the {@link XMLReader} is
 * not initialised.
 *
 * @param handler The content handler to use.
 * 
 * @return The requested {@link XMLReader}
 * 
 * @throws SAXException Should a SAX exception occur
 * @throws ParserConfigurationException Should a parser config exception occur
 */
public static XMLReader makeXMLReader(ContentHandler handler)
        throws SAXException, ParserConfigurationException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    XMLReader reader = factory.newSAXParser().getXMLReader();
    if (handler != null) {
        reader.setContentHandler(handler);
    }
    return reader;
}

From source file:net.eledge.android.europeana.tools.RssReader.java

public static List<BlogArticle> readFeed(String url, DateTime lastViewed) {
    InputStream is = null;/*from   ww  w  .ja v  a 2  s.c  o m*/
    try {
        HttpGet request = new HttpGet(url);
        AndroidHttpClient.modifyRequestToAcceptGzipResponse(request);
        HttpResponse response = new DefaultHttpClient().execute(request);
        is = AndroidHttpClient.getUngzippedContent(response.getEntity());

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        RssFeedHandler rh = new RssFeedHandler(lastViewed);

        xr.setContentHandler(rh);
        xr.parse(new InputSource(is));

        return rh.articles;
    } catch (IOException | SAXException | ParserConfigurationException e) {
        Log.e("RssReader", e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    return null;
}

From source file:net.sf.janos.model.xml.ResultParser.java

/**
 * @param xml/*www  .  j a  v a 2 s .  com*/
 * @return a list of Entrys from the given xml string.
 * @throws IOException
 * @throws SAXException
 */
public static List<Entry> getEntriesFromStringResult(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    EntryHandler handler = new EntryHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse entries: ", e);
    }
    return handler.getArtists();
}

From source file:net.sf.janos.model.xml.ResultParser.java

public static TrackMetaData parseTrackMetaData(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    TrackMetaDataHandler handler = new TrackMetaDataHandler();
    reader.setContentHandler(handler);
    try {/*from w w w.  jav a2 s.com*/
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse AV Transport Event: ", e);
    }
    return handler.getMetaData();
}

From source file:net.sf.janos.model.xml.ResultParser.java

/**
 * @param controller/*from w ww. j  a  v  a  2s  . c  o m*/
 * @param xml
 * @return zone group state from the given xml
 * @throws IOException
 * @throws SAXException
 */
public static ZoneGroupState getGroupStateFromResult(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    ZoneGroupStateHandler handler = new ZoneGroupStateHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        LOG.error("Could not parse group state: ", e);
    }

    return new ZoneGroupState(handler.getGroups());

}