All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.remal.javax.xml.transform.Transformer.kt Maven / Gradle / Ivy

package name.remal

import org.w3c.dom.Document
import org.w3c.dom.DocumentFragment
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.io.*
import java.net.URI
import java.net.URL
import javax.xml.transform.OutputKeys
import javax.xml.transform.Result
import javax.xml.transform.Source
import javax.xml.transform.Transformer

fun Transformer.tryToSetOutputProperty(name: String, value: String?) {
    try {
        setOutputProperty(name, value)
    } catch (ignored: IllegalArgumentException) {
        /* unsupported by this transformer */
    }
}

fun <T : Transformer> T.withIndention(indentSize: Int = 4): T = this.apply {
    setOutputProperty(OutputKeys.INDENT, if (1 <= indentSize) "yes" else "no")

    if (1 <= indentSize) {
        arrayOf(
            "{http://xml.apache.org/xslt}indent-amount",
            "{http://saxon.sf.net/}indent-spaces"
        ).forEach { name ->
            tryToSetOutputProperty(name, indentSize.toString())
        }
    }
}

fun Transformer.transform(source: Source) = TransformerWithSource(this, source)
fun Transformer.transform(url: URL) = this.transform(newTransformSource(url))
fun Transformer.transform(file: File) = this.transform(newTransformSource(file))
fun Transformer.transform(inputStream: InputStream, location: URI? = null) = this.transform(newTransformSource(inputStream, location))
fun Transformer.transform(reader: Reader, location: URI? = null) = this.transform(newTransformSource(reader, location))
fun Transformer.transform(node: Node, location: URI? = null) = this.transform(newTransformSource(node, location))
fun Transformer.transform(string: String, location: URI? = null) = this.transform(newTransformSource(string, location))

class TransformerWithSource(
    private val transformer: Transformer,
    private val source: Source
) {

    fun into(result: Result) {
        transformer.transform(source, result)
    }

    fun into(outputStream: OutputStream, location: URI? = null) = into(newTransformResult(outputStream, location))
    fun into(writer: Writer, location: URI? = null) = into(newTransformResult(writer, location))
    fun into(document: Document, location: URI? = null) = into(newTransformResult(document, location))
    fun into(documentFragment: DocumentFragment, location: URI? = null) = into(newTransformResult(documentFragment, location))
    fun into(element: Element, location: URI? = null) = into(newTransformResult(element, location))

    fun intoString(location: URI? = null): String = StringWriter().use { into(it, location); it.toString() }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy