Java : TransformerFactory (XML) 示例

TransformerFactory (Java SE 22 & JDK 22) 示例。
您将在大多数 TransformerFactory 方法中找到代码示例。

注解 :

  • 本文可能使用了翻译软件以方便阅读。 另请查看英文原文

简介

TransformerFactory 实例可用于创建 Transformer 和 Templates 对象。 (机器翻译)

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

默认构造函数是故意保护的。 (机器翻译)

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)

通过符合给定条件的 xml-stylesheet 处理指令获取与 XML 源文档相关的样式表规范。 (机器翻译)

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)

允许用户检索底层实现的特定属性。 (机器翻译)

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

获取 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)

查找某个特征的值。 (机器翻译)

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

获取转换过程中默认使用的对象,以解析 document()、xsl:import 或 xsl:include 中使用的 URI。 (机器翻译)

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

创建 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.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 ()

获取 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)

从工厂类名获取 TransformerFactory 的新实例。 (机器翻译)

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

abstract Templates newTemplates (Source 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 ()

创建一个新的Transformer,执行从源到结果的复制,即“身份变换”。 (机器翻译)

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)

将源处理成转换器对象。 (机器翻译)

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)

允许用户在底层实现上设置特定属性。 (机器翻译)

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)

为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 void setFeature (String name, boolean value)

为此 TransformerFactory 以及由此工厂创建的变压器或模板设置一个功能。 (机器翻译)

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)

设置在转换过程中默认使用的对象来解析 document()、xsl:import 或 xsl:include 中使用的 URI。 (机器翻译)

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>
}

相关文章

To top of page