Example usage for javax.xml.transform.sax SAXSource FEATURE

List of usage examples for javax.xml.transform.sax SAXSource FEATURE

Introduction

In this page you can find the example usage for javax.xml.transform.sax SAXSource FEATURE.

Prototype

String FEATURE

To view the source code for javax.xml.transform.sax SAXSource FEATURE.

Click Source Link

Document

If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Source input of this type.

Usage

From source file:Pipe.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    // Instantiate  a TransformerFactory.
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // Determine whether the TransformerFactory supports The use uf SAXSource 
    // and SAXResult
    if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) {
        // Cast the TransformerFactory to SAXTransformerFactory.
        SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
        // Create a TransformerHandler for each stylesheet.
        TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource("foo1.xsl"));
        TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource("foo2.xsl"));
        TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource("foo3.xsl"));

        // Create an XMLReader.
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(tHandler1);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler1);

        tHandler1.setResult(new SAXResult(tHandler2));
        tHandler2.setResult(new SAXResult(tHandler3));

        // transformer3 outputs SAX events to the serializer.
        java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
        xmlProps.setProperty("indent", "yes");
        xmlProps.setProperty("standalone", "no");
        Serializer serializer = SerializerFactory.getSerializer(xmlProps);
        serializer.setOutputStream(System.out);
        tHandler3.setResult(new SAXResult(serializer.asContentHandler()));

        // Parse the XML input document. The input ContentHandler and output ContentHandler
        // work in separate threads to optimize performance.   
        reader.parse("foo.xml");
    }//from w  ww .j  a  v  a 2  s.  co m
}

From source file:UseXMLFilters.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    // Instantiate  a TransformerFactory.
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // Determine whether the TransformerFactory supports The use uf SAXSource 
    // and SAXResult
    if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) {
        // Cast the TransformerFactory to SAXTransformerFactory.
        SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
        // Create an XMLFilter for each stylesheet.
        XMLFilter xmlFilter1 = saxTFactory.newXMLFilter(new StreamSource("foo1.xsl"));
        XMLFilter xmlFilter2 = saxTFactory.newXMLFilter(new StreamSource("foo2.xsl"));
        XMLFilter xmlFilter3 = saxTFactory.newXMLFilter(new StreamSource("foo3.xsl"));

        // Create an XMLReader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        // xmlFilter1 uses the XMLReader as its reader.
        xmlFilter1.setParent(reader);/*  w  w  w  . j  ava  2 s .  com*/

        // xmlFilter2 uses xmlFilter1 as its reader.
        xmlFilter2.setParent(xmlFilter1);

        // xmlFilter3 uses xmlFilter2 as its reader.
        xmlFilter3.setParent(xmlFilter2);

        // xmlFilter3 outputs SAX events to the serializer.
        java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
        xmlProps.setProperty("indent", "yes");
        xmlProps.setProperty("standalone", "no");
        Serializer serializer = SerializerFactory.getSerializer(xmlProps);
        serializer.setOutputStream(System.out);
        xmlFilter3.setContentHandler(serializer.asContentHandler());

        // Perform the series of transformations as follows:
        //   - transformer3 gets its parent (transformer2) as the XMLReader/XMLFilter
        //     and calls transformer2.parse(new InputSource("foo.xml")).
        //   - transformer2 gets its parent (transformer1) as the XMLReader/XMLFilter
        //     and calls transformer1.parse(new InputSource("foo.xml")). 
        //   - transformer1 gets its parent (reader, a SAXParser) as the XMLReader 
        //     and calls reader.parse(new InputSource("foo.xml")).
        //   - reader parses the XML document and sends the SAX parse events to transformer1, 
        //     which performs transformation 1 and sends the output to transformer2.
        //   - transformer2 parses the transformation 1 output, performs transformation 2, and 
        //     sends the output to transformer3.
        //   - transformer3 parses the transformation 2 output, performs transformation 3,
        //     and sends the output to the serializer.
        xmlFilter3.parse(new InputSource("foo.xml"));
    }
}

From source file:SAX2SAX.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {

    // Instantiate a TransformerFactory.
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // Determine whether the TransformerFactory supports The use of SAXSource 
    // and SAXResult
    if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) {
        // Cast the TransformerFactory.
        SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
        // Create a ContentHandler to handle parsing of the stylesheet.
        TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler();

        // Create an XMLReader and set its ContentHandler.
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(templatesHandler);

        // Parse the stylesheet.                       
        reader.parse("birds.xsl");

        //Get the Templates object from the ContentHandler.
        Templates templates = templatesHandler.getTemplates();
        // Create a ContentHandler to handle parsing of the XML source.  
        TransformerHandler handler = saxTFactory.newTransformerHandler(templates);
        // Reset the XMLReader's ContentHandler.
        reader.setContentHandler(handler);

        // Set the ContentHandler to also function as a LexicalHandler, which
        // includes "lexical" events (e.g., comments and CDATA). 
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        FileOutputStream fos = new FileOutputStream("birds.out");

        java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
        xmlProps.setProperty("indent", "yes");
        xmlProps.setProperty("standalone", "no");
        Serializer serializer = SerializerFactory.getSerializer(xmlProps);
        serializer.setOutputStream(fos);

        // Set the result handling to be a serialization to the file output stream.
        Result result = new SAXResult(serializer.asContentHandler());
        handler.setResult(result);/* w w  w .j a v  a  2  s .co m*/

        // Parse the XML input document.
        reader.parse("birds.xml");

        System.out.println("************* The result is in birds.out *************");
    } else
        System.out.println("The TransformerFactory does not support SAX input and SAX output");
}

From source file:Main.java

private static void transformInternal(final URIResolver xslResolver, final StreamSource xml,
        final InputSource xsl, final Map<String, Object> parameters, final StreamResult result)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException {//from ww w .  java 2 s  . c o m
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setURIResolver(xslResolver);

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // if so, we can safely cast
        final SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // create a Templates ContentHandler to handle parsing of the
        // stylesheet
        final javax.xml.transform.sax.TemplatesHandler templatesHandler = stfactory.newTemplatesHandler();
        templatesHandler.setDocumentLocator(emptyDocumentLocator);

        final XMLFilter filter = new XMLFilterImpl();
        filter.setParent(makeXMLReader());
        filter.setContentHandler(templatesHandler);

        // parse the stylesheet
        templatesHandler.setSystemId(xsl.getSystemId());
        filter.parse(xsl);

        // set xslt parameters
        final Transformer autobot = templatesHandler.getTemplates().newTransformer();
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                final String name = keys.next();
                final Object value = parameters.get(name);
                autobot.setParameter(name, value);
            }
        }

        // set saxon parameters
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String name = keys.next();
                if (name.startsWith("saxon-")) {
                    final String value = parameters.get(name).toString();
                    name = name.replaceFirst("saxon\\-", "");
                    autobot.setOutputProperty(name, value);
                }
            }
        }

        // do the transform
        // logger.debug("SAX resolving systemIDs relative to: " +
        // templatesHandler.getSystemId());
        autobot.transform(xml, result);

    } else {
        throw new IllegalStateException("Factory doesn't implement SAXTransformerFactory");
    }
}

From source file:ValidateXMLInput.java

void validate() throws Exception {
    // Since we're going to use a SAX feature, the transformer must support 
    // input in the form of a SAXSource.
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // Standard way of creating an XMLReader in JAXP 1.1.
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setNamespaceAware(true); // Very important!
        // Turn on validation.
        pfactory.setValidating(true);//from  w  w  w.ja v  a  2 s.co  m
        // Get an XMLReader.
        XMLReader reader = pfactory.newSAXParser().getXMLReader();

        // Instantiate an error handler (see the Handler inner class below) that will report any
        // errors or warnings that occur as the XMLReader is parsing the XML input.
        Handler handler = new Handler();
        reader.setErrorHandler(handler);

        // Standard way of creating a transformer from a URL.
        Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl"));

        // Specify a SAXSource that takes both an XMLReader and a URL.
        SAXSource source = new SAXSource(reader, new InputSource("birds.xml"));

        // Transform to a file.
        try {
            t.transform(source, new StreamResult("birds.out"));
        } catch (TransformerException te) {
            // The TransformerException wraps someting other than a SAXParseException
            // warning or error, either of which should be "caught" by the Handler.
            System.out.println("Not a SAXParseException warning or error: " + te.getMessage());
        }

        System.out.println("=====Done=====");
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:net.sf.joost.trax.TransformerFactoryImpl.java

/**
 * Supplied features.//w ww.  j a  v a 2 s.c o  m
 * @param name Name of the feature.
 * @return true if feature is supported.
 */
public boolean getFeature(String name) {

    if (name.equals(SAXSource.FEATURE)) {
        return true;
    }
    if (name.equals(SAXResult.FEATURE)) {
        return true;
    }
    if (name.equals(DOMSource.FEATURE)) {
        return true;
    }
    if (name.equals(DOMResult.FEATURE)) {
        return true;
    }
    if (name.equals(StreamSource.FEATURE)) {
        return true;
    }
    if (name.equals(StreamResult.FEATURE)) {
        return true;
    }
    if (name.equals(SAXTransformerFactory.FEATURE)) {
        return true;
    }
    if (name.equals(SAXTransformerFactory.FEATURE_XMLFILTER)) {
        return true;
    }

    String errMsg = "Unknown feature " + name;
    TransformerConfigurationException tE = new TransformerConfigurationException(errMsg);

    try {
        defaultErrorListener.error(tE);
        return false;
    } catch (TransformerException e) {
        throw new IllegalArgumentException(errMsg);
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and SAX events out.
 *///from w w w  .j a  va2  s.c om
public static void exampleContentHandlerToContentHandler(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // If so, we can safely cast.
        SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // A TransformerHandler is a ContentHandler that will listen for 
        // SAX events, and transform them to the result.
        TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID));

        // Set the result handling to be a serialization to System.out.
        Result result = new SAXResult(new ExampleContentHandler());
        handler.setResult(result);

        // Create a reader, and set it's content handler to be the TransformerHandler.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);

        // It's a good idea for the parser to send lexical events.
        // The TransformerHandler is also a LexicalHandler.
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Parse the source XML, and send the parse events to the TransformerHandler.
        reader.parse(sourceID);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:Examples.java

/**
 * Show the Transformer as a SAX2 XMLReader.  An XMLFilter obtained 
 * from newXMLFilter should act as a transforming XMLReader if setParent is not
 * called.  Internally, an XMLReader is created as the parent for the XMLFilter.
 *///from  w w  w  .j a  v  a2  s . c  om
public static void exampleXMLReader(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException // , ParserConfigurationException
{
    TransformerFactory tfactory = TransformerFactory.newInstance();
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        XMLReader reader = ((SAXTransformerFactory) tfactory).newXMLFilter(new StreamSource(xslID));

        reader.setContentHandler(new ExampleContentHandler());

        reader.parse(new InputSource(sourceID));
    } else
        System.out.println("tfactory does not support SAX features!");
}

From source file:Examples.java

/**
 * This example shows how to chain events from one Transformer
 * to another transformer, using the Transformer as a
 * SAX2 XMLFilter/XMLReader.//from w ww. j  a  v a2 s .c o m
 */
public static void exampleXMLFilterChain(String sourceID, String xslID_1, String xslID_2, String xslID_3)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1));
    Transformer transformer1 = stylesheet1.newTransformer();

    // If one success, assume all will succeed.
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();

        XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1));
        XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2));
        XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3));

        if (null != filter1) // If one success, assume all were success.
        {
            // transformer1 will use a SAX parser as it's reader.    
            filter1.setParent(reader);

            // transformer2 will use transformer1 as it's reader.
            filter2.setParent(filter1);

            // transform3 will use transform2 as it's reader.
            filter3.setParent(filter2);

            filter3.setContentHandler(new ExampleContentHandler());
            // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());

            // Now, when you call transformer3 to parse, it will set  
            // itself as the ContentHandler for transform2, and 
            // call transform2.parse, which will set itself as the 
            // content handler for transform1, and call transform1.parse, 
            // which will set itself as the content listener for the 
            // SAX parser, and call parser.parse(new InputSource("xml/foo.xml")).
            filter3.parse(new InputSource(sourceID));
        } else {
            System.out.println("Can't do exampleXMLFilter because " + "tfactory doesn't support asXMLFilter()");
        }
    } else {
        System.out.println("Can't do exampleXMLFilter because " + "tfactory is not a SAXTransformerFactory");
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and DOM nodes out.
 *//*from  w  w w  . java 2 s. c o  m*/
public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Make sure the transformer factory we obtained supports both
    // DOM and SAX.
    if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) {
        // We can now safely cast to a SAXTransformerFactory.
        SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

        // Create an Document node as the root for the output.
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();

        // Create a ContentHandler that can liston to SAX events 
        // and transform the output to DOM nodes.
        TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID));
        handler.setResult(new DOMResult(outNode));

        // Create a reader and set it's ContentHandler to be the 
        // transformer.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Send the SAX events from the parser to the transformer,
        // and thus to the DOM tree.
        reader.parse(sourceID);

        // Serialize the node for diagnosis.
        exampleSerializeNode(outNode);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}