Java : TransformerFactory (XML) con ejemplos

TransformerFactory (Java SE 22 & JDK 22) en Java con ejemplos.
Encontrará ejemplos de código en la mayoría de los métodos de TransformerFactory.

Nota :


Summary

Se puede utilizar una instancia de TransformerFactory para crear objetos Transformer y Plantillas. (Traducción automática)

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

El constructor predeterminado está protegido a propósito. (Traducción automática)

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)

Obtenga las especificaciones de la hoja de estilo asociadas con el documento fuente XML a través de la instrucción de procesamiento xml-stylesheet que coincidan con los criterios dados. (Traducción automática)

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)

Permite al usuario recuperar atributos específicos en la implementación subyacente. (Traducción automática)

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

Obtenga el controlador de eventos de error para TransformerFactory. (Traducción automática)

// 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)

Busque el valor de una característica. (Traducción automática)

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

Obtenga el objeto que se utiliza de forma predeterminada durante la transformación para resolver las URI utilizadas en document(), xsl:import o xsl:include. (Traducción automática)

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

Crea una nueva instancia de la implementación predeterminada del sistema incorporada de TransformerFactory. (Traducción automática)

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

Obtiene una nueva instancia de un TransformerFactory. (Traducción automática)

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)

Obtenga una nueva instancia de un TransformerFactory a partir del nombre de clase de fábrica. (Traducción automática)

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

abstract Templates newTemplates (Source source)

Procesar la fuente en un objeto Plantillas, que es una representación compilada de la fuente. (Traducción automática)

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

Crea un nuevo Transformador que realice una copia de la Fuente al Resultado, es decir, la "transformación de identidad". (Traducción automática)

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)

Procesar la fuente en un objeto transformador. (Traducción automática)

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)

Permite al usuario establecer atributos específicos en la implementación subyacente. (Traducción automática)

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)

Establezca el detector de eventos de error para TransformerFactory, que se utiliza para el procesamiento de instrucciones de transformación, y no para la transformación en sí. (Traducción automática)

// 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)

Establezca una función para esta TransformerFactory y los Transformers o Plantillas creados por esta fábrica. (Traducción automática)

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)

Establezca un objeto que se utiliza de forma predeterminada durante la transformación para resolver las URI utilizadas en document(), xsl:import o xsl:include. (Traducción automática)

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