Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to write XML 1.1 documents in Java

Tags:

java

xml

How do you write an XML version 1.1 document in Java? Java only seems to support version 1.0.

I tried using the OutputKeys.VERSION output property, as shown below, but that had 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 JVMs:

  • Linux: OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-1~deb7u1)
  • Linux: Java(TM) SE Runtime Environment (build 1.8.0_25-b17)

I'd rather not have to include any external libraries, if possible. Thank you.

like image 399
Michael Avatar asked Aug 09 '15 14:08

Michael


1 Answers

I'm using jdk1.8.0_40-b26 under Linux, if I run your code I obtain:

<?xml version="1.0" encoding="UTF-8"?>

But if I add xalan-2.7.2 in my maven dependencies, I obtain:

<?xml version="1.1" encoding="UTF-8"?>

The explanation is that the xml librairies bundled with the jdk are quite old and the best solution is to use external librairies.

Reading the documentation, we see that the versions included in the reference implementation should be

Xerces version 2.6.2 + (Xerces version 2.6.2 with controlled bug fixes)

XSLTC version 2.6.0 + (XSLTC version 2.6.0 , with controlled bug fixes, based on the Xalan 2.6.0 release)

Just to confirm, I add xalan-2.6.0 in my maven dependencies, and I obtain again

<?xml version="1.0" encoding="UTF-8"?>

So if you want to use XML 1.1, you have to use recent external xml libraries like Xerces 2.11 and Xalan 2.7.2.

like image 110
Ortomala Lokni Avatar answered Nov 09 '22 23:11

Ortomala Lokni