Skip to content

Instantly share code, notes, and snippets.

@andirady
Last active September 17, 2021 23:25
Show Gist options
  • Save andirady/82a8407523a45453541a7f9ef2802462 to your computer and use it in GitHub Desktop.
Save andirady/82a8407523a45453541a7f9ef2802462 to your computer and use it in GitHub Desktop.
xmlformatter-native-image
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
JAR=xmlformatter.jar
XmlFormatter.class: XmlFormatter.java
javac XmlFormatter.java
$(JAR): XmlFormatter.class formatter.xlst
jar --create --file $(JAR) --main-class=XmlFormatter XmlFormatter.class formatter.xlst
cfg: $(JAR)
java -agentlib:native-image-agent=config-output-dir=cfg -jar $(JAR) test.xml
xmlformatter: cfg
native-image --verbose -H:ConfigurationFileDirectories=cfg -H:+AllowIncompleteClasspath -jar $(JAR)
<point><x>1</x><y>y</y></point>
import java.io.*;
import java.nio.file.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class XmlFormatter {
public static void main(String[] args) throws Exception {
var xmlPath = Path.of(args[0]);
var dbf = DocumentBuilderFactory.newInstance();
var db = dbf.newDocumentBuilder();
Document doc;
try (var is = Files.newInputStream(xmlPath)) {
doc = db.parse(is);
}
var tf = TransformerFactory.newInstance();
Transformer transformer;
try (var xlst = XmlFormatter.class.getClassLoader().getResourceAsStream("formatter.xlst")) {
System.out.println("xlst = " + xlst);
transformer = tf.newTransformer(new StreamSource(xlst));
}
var domSource = new DOMSource(doc);
try (var os = Files.newOutputStream(xmlPath)) {
var streamResult = new StreamResult(os);
transformer.transform(domSource, streamResult);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment