There is my old working code what rewrite an xml file:
private static void rewriteXmlDocument(Document document, File xmlFile) throws TransformerException,
FileNotFoundException {
File temporaryFile = new File(xmlFile.getParent() + File.separator + "temporary.xml"); // write to a temporary file
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
if (temporaryFile.exists()) temporaryFile.delete(); // there is a trash
StreamResult result = new StreamResult(new FileOutputStream(temporaryFile));
transformer.transform(source, result);
xmlFile.delete(); // write succeeded, now we can delete the old
temporaryFile.renameTo(xmlFile); // rename temporary to old name
}
If I add these two dependency to pom.xml (and some code for finding in a docx), I receive an exception from the transformerFactory.newTransformer() row.
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>6.1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
Exception is:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xml/serializer/TreeWalker
at org.apache.xalan.processor.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:818)
at AnanlyzeEmails/AnalyzeEmailsApplication.AnalyzeEmailsApp.rewriteXmlDocument(AnalyzeEmailsApp.java:170)
How can I use my old xml manipulation code beside jaxb?
1 Answer 1
You need to change your code to load a specific TransformerFactory rather than loading the first one it finds on the classpath. I don't know specifically why your code is failing but this is a common problem with JAXPs use of the Java service provider mechanism - different implementations of TransformerFactory are not sufficiently compatible to make them fully interchangeable. You probably want to load the default system-provided TransformerFactory: since Java 9 you can do this using TransformerFactory.getDefaultInstance().
TransformerFactory.newInstance()toTransformerFactory.newDefaultInstance()to always get the built-in transformer, no matter what additional dependencies have been added to the environment.