XML 1.1 documents cannot be written in Java
How do you write XML version 1.1 documents in Java? Java seems to support only version 1.0
I try to use outputkeys Version output attribute, as shown below, but has no effect:
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = fact.newDocumentBuilder(); Document doc = db.newDocument(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.VERSION,"1.1"); DOMSource source = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source,result); System.out.println(writer.toString()); //still produces a 1.0 XML document
I tested the above code in the following JVM:
>Linux: openjdk runtime environment (icedtea 2.5.5) (7u79-2.5.5-1 ~ deb7u1) > linux: Java (TM) se runtime environment (version 1.8.0_25-b17)
If possible, I prefer not to include any external libraries thank you.
Solution
I use jdk1.0 under Linux 8.0_ 40-b26, if I run your code, I get:
<?xml version="1.0" encoding="UTF-8"?>
But if I add xalan-2.7. To Maven dependencies 2. I will get:
<?xml version="1.1" encoding="UTF-8"?>
The explanation is that the XML library bundled with JDK is very old, and the best solution is to use an external library
After reading the documentation, we can see that the version included in the reference implementation should be
To confirm, I added xalan-2.6.0 to my Maven dependency 0, and then I get it again
<?xml version="1.0" encoding="UTF-8"?>
Therefore, if you want to use XML 1.1, you must use the latest external XML libraries, such as Xerces 2.11 and xalan 2.7 two