Java : TransformerFactory (XML) with Examples

TransformerFactory (Java SE 22 & JDK 22) with Examples.
You will find code examples on most TransformerFactory methods.


Summary

A TransformerFactory instance can be used to create Transformer and Templates objects.

Class diagram

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var text = document.createTextNode("abcd");
root.appendChild(text);

final var transformerFactory = TransformerFactory.newInstance();
final var transformer = transformerFactory.newTransformer();

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<?xml version="1.0" encoding="UTF-8" standalone="no"?><root>abcd</root>

Constructors

TransformerFactory ()

Default constructor is protected on purpose.

protected. I think it's rare to create a subclass of this class. Therefore, the code example is omitted.

Methods

abstract Source getAssociatedStylesheet (Source source, String media, String title, String charset)

Get the stylesheet specification(s) associated with the XML Source document via the xml-stylesheet processing instruction that match the given criteria.

final var file = Path.of("R:", "java-work", "sample.xsl");
System.out.println(file); // R:\java-work\sample.xsl

Files.writeString(file, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
          <xsl:output omit-xml-declaration="yes" />

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <?xml-stylesheet type="text/xsl" href="file:///R:/java-work/sample.xsl"?>
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var transformerFactory = TransformerFactory.newInstance();

final var stylesheet = transformerFactory.getAssociatedStylesheet(
        new DOMSource(document), null, null, null);

final var transformer = transformerFactory.newTransformer(stylesheet);

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<xxx>abcd</xxx>

abstract Object getAttribute (String name)

Allows the user to retrieve specific attributes on the underlying implementation.

final var file = Path.of("R:", "java-work", "sample.xsl");
System.out.println(file); // R:\java-work\sample.xsl

Files.writeString(file, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
          <xsl:output omit-xml-declaration="yes" />

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var xsl = """
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:import href="file:///R:/java-work/sample.xsl"/>
        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

{
    final var ret = transformerFactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
    System.out.println(ret); // "all"

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<xxx>abcd</xxx>
}

transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

{
    final var ret = transformerFactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
    System.out.println(ret); // ""

    try {
        final var transformer = transformerFactory.newTransformer(
                new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
    } catch (TransformerConfigurationException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //javax.xml.transform.TransformerConfigurationException: line 2:
    // Could not read stylesheet target 'sample.xsl', because 'file' access is not allowed
    // due to restriction set by the accessExternalStylesheet property.
}

abstract ErrorListener getErrorListener ()

Get the error event handler for the TransformerFactory.

// An XSL text with an invalid attribute name.
final var xsl = """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="/">
            <xsl:attribute name="xmlns"/>
          </xsl:template>

        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

System.out.println(transformerFactory.getErrorListener() != null); // true

final var listener = new ErrorListener() {
    @Override
    public void warning(TransformerException exception) {
        System.out.println("ErrorListener warning : " + exception);
    }

    @Override
    public void error(TransformerException exception) {
        System.out.println("ErrorListener error : " + exception);
    }

    @Override
    public void fatalError(TransformerException exception) {
        System.out.println("ErrorListener fatalError : " + exception);
    }
};

transformerFactory.setErrorListener(listener);
System.out.println(listener == transformerFactory.getErrorListener()); // true

try {
    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
} catch (TransformerConfigurationException e) {
    System.out.println("TransformerConfigurationException : " + e);
}

// Result
// ↓
//ErrorListener error : javax.xml.transform.TransformerException:
// line 4: You cannot call an attribute 'xmlns'
//ErrorListener fatalError : javax.xml.transform.TransformerConfigurationException:
// line 4: You cannot call an attribute 'xmlns'
//TransformerConfigurationException : javax.xml.transform.TransformerConfigurationException:
// line 4: You cannot call an attribute 'xmlns'

abstract boolean getFeature (String name)

Look up the value of a feature.

final var factory = TransformerFactory.newInstance();

final var ret1 = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
System.out.println(ret1); // false

final var ret2 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
System.out.println(ret2); // "all"

final var ret3 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
System.out.println(ret3); // "all"

factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

final var ret4 = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
System.out.println(ret4); // true

final var ret5 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
System.out.println(ret5); // ""

final var ret6 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
System.out.println(ret6); // ""

abstract URIResolver getURIResolver ()

Get the object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

final var sampleX = Path.of("R:", "java-work", "sample-x.xsl");
System.out.println(sampleX); // R:\java-work\sample-x.xsl

Files.writeString(sampleX, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var sampleY = Path.of("R:", "java-work", "sample-y.xsl");
System.out.println(sampleY); // R:\java-work\sample-y.xsl

Files.writeString(sampleY, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="root">
            <yyy>
              <xsl:value-of select="." />
            </yyy>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var xsl = """
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:import href="file:///R:/java-work/sample-x.xsl"/>
          <xsl:output omit-xml-declaration="yes"/>
        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

{
    System.out.println(transformerFactory.getURIResolver()); // null

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<xxx>abcd</xxx>
}

final var resolver = new URIResolver() {
    @Override
    public Source resolve(String href, String base) {
        if ("file:///R:/java-work/sample-x.xsl".equals(href)) {
            return new StreamSource("file:///R:/java-work/sample-y.xsl");
        }
        return null;
    }
};
transformerFactory.setURIResolver(resolver);

{
    System.out.println(transformerFactory.getURIResolver() != null); // true

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<yyy>abcd</yyy>
}

static TransformerFactory newDefaultInstance ()

Creates a new instance of the TransformerFactory builtin system-default implementation.

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var text = document.createTextNode("abcd");
root.appendChild(text);

final var transformerFactory = TransformerFactory.newDefaultInstance();

final var transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<root>abcd</root>

static TransformerFactory newInstance ()

Obtains a new instance of a TransformerFactory.

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var text = document.createTextNode("abcd");
root.appendChild(text);

final var transformerFactory = TransformerFactory.newInstance();

final var transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<root>abcd</root>

static TransformerFactory newInstance (String factoryClassName, ClassLoader classLoader)

Obtain a new instance of a TransformerFactory from factory class name.

This method is probably for third party libraries. Therefore, the code example is omitted.

abstract Templates newTemplates (Source source)

Process the Source into a Templates object, which is a a compiled representation of the source.

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var xsl = """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
          <xsl:output omit-xml-declaration="yes"/>

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();
final var templates = transformerFactory.newTemplates(
        new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

final var transformer = templates.newTransformer();

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<xxx>abcd</xxx>

abstract Transformer newTransformer ()

Create a new Transformer that performs a copy of the Source to the Result, i.e. the "identity transform".

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.newDocument();

final var root = document.createElement("root");
document.appendChild(root);

final var text = document.createTextNode("abcd");
root.appendChild(text);

final var transformerFactory = TransformerFactory.newInstance();

final var transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<root>abcd</root>

abstract Transformer newTransformer (Source source)

Process the Source into a Transformer Object.

final var file = Path.of("R:", "java-work", "sample.xsl");
System.out.println(file); // R:\java-work\sample.xsl

Files.writeString(file, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
          <xsl:output omit-xml-declaration="yes" />

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <?xml-stylesheet type="text/xsl" href="file:///R:/java-work/sample.xsl"?>
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var transformerFactory = TransformerFactory.newInstance();

final var stylesheet = transformerFactory.getAssociatedStylesheet(
        new DOMSource(document), null, null, null);

final var transformer = transformerFactory.newTransformer(stylesheet);

final var result = new StreamResult(new StringWriter());
transformer.transform(new DOMSource(document), result);

System.out.println(result.getWriter());

// Result
// ↓
//<xxx>abcd</xxx>

abstract void setAttribute (String name, Object value)

Allows the user to set specific attributes on the underlying implementation.

final var file = Path.of("R:", "java-work", "sample.xsl");
System.out.println(file); // R:\java-work\sample.xsl

Files.writeString(file, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
          <xsl:output omit-xml-declaration="yes" />

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var xsl = """
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:import href="file:///R:/java-work/sample.xsl"/>
        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

{
    final var ret = transformerFactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
    System.out.println(ret); // "all"

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<xxx>abcd</xxx>
}

transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

{
    final var ret = transformerFactory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
    System.out.println(ret); // ""

    try {
        final var transformer = transformerFactory.newTransformer(
                new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
    } catch (TransformerConfigurationException e) {
        System.out.println(e);
    }

    // Result
    // ↓
    //javax.xml.transform.TransformerConfigurationException: line 2:
    // Could not read stylesheet target 'sample.xsl', because 'file' access is not allowed
    // due to restriction set by the accessExternalStylesheet property.
}

abstract void setErrorListener (ErrorListener listener)

Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.

// An XSL text with an invalid attribute name.
final var xsl = """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="/">
            <xsl:attribute name="xmlns"/>
          </xsl:template>

        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

System.out.println(transformerFactory.getErrorListener() != null); // true

final var listener = new ErrorListener() {
    @Override
    public void warning(TransformerException exception) {
        System.out.println("ErrorListener warning : " + exception);
    }

    @Override
    public void error(TransformerException exception) {
        System.out.println("ErrorListener error : " + exception);
    }

    @Override
    public void fatalError(TransformerException exception) {
        System.out.println("ErrorListener fatalError : " + exception);
    }
};

transformerFactory.setErrorListener(listener);
System.out.println(listener == transformerFactory.getErrorListener()); // true

try {
    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));
} catch (TransformerConfigurationException e) {
    System.out.println("TransformerConfigurationException : " + e);
}

// Result
// ↓
//ErrorListener error : javax.xml.transform.TransformerException:
// line 4: You cannot call an attribute 'xmlns'
//ErrorListener fatalError : javax.xml.transform.TransformerConfigurationException:
// line 4: You cannot call an attribute 'xmlns'
//TransformerConfigurationException : javax.xml.transform.TransformerConfigurationException:
// line 4: You cannot call an attribute 'xmlns'

abstract void setFeature (String name, boolean value)

Set a feature for this TransformerFactory and Transformers or Templates created by this factory.

final var factory = TransformerFactory.newInstance();

final var ret1 = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
System.out.println(ret1); // false

final var ret2 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
System.out.println(ret2); // "all"

final var ret3 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
System.out.println(ret3); // "all"

factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

final var ret4 = factory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING);
System.out.println(ret4); // true

final var ret5 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_DTD);
System.out.println(ret5); // ""

final var ret6 = factory.getAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET);
System.out.println(ret6); // ""

abstract void setURIResolver (URIResolver resolver)

Set an object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

final var sampleX = Path.of("R:", "java-work", "sample-x.xsl");
System.out.println(sampleX); // R:\java-work\sample-x.xsl

Files.writeString(sampleX, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="root">
            <xxx>
              <xsl:value-of select="." />
            </xxx>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var sampleY = Path.of("R:", "java-work", "sample-y.xsl");
System.out.println(sampleY); // R:\java-work\sample-y.xsl

Files.writeString(sampleY, """
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

          <xsl:template match="root">
            <yyy>
              <xsl:value-of select="." />
            </yyy>
          </xsl:template>

        </xsl:stylesheet>
        """);

final var xml = """
        <root>abcd</root>
        """;

final var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final var document = builder.parse(new ByteArrayInputStream(xml.getBytes()));

final var xsl = """
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
          <xsl:import href="file:///R:/java-work/sample-x.xsl"/>
          <xsl:output omit-xml-declaration="yes"/>
        </xsl:stylesheet>
        """;

final var transformerFactory = TransformerFactory.newInstance();

{
    System.out.println(transformerFactory.getURIResolver()); // null

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<xxx>abcd</xxx>
}

final var resolver = new URIResolver() {
    @Override
    public Source resolve(String href, String base) {
        if ("file:///R:/java-work/sample-x.xsl".equals(href)) {
            return new StreamSource("file:///R:/java-work/sample-y.xsl");
        }
        return null;
    }
};
transformerFactory.setURIResolver(resolver);

{
    System.out.println(transformerFactory.getURIResolver() != null); // true

    final var transformer = transformerFactory.newTransformer(
            new StreamSource(new ByteArrayInputStream(xsl.getBytes())));

    final var result = new StreamResult(new StringWriter());
    transformer.transform(new DOMSource(document), result);

    System.out.println(result.getWriter());

    // Result
    // ↓
    //<yyy>abcd</yyy>
}

Related posts

To top of page