I am using org.jdom2 to parse xml files. I need to know if the file is marked as version 1.1 or version 1.0. How do I access the xml declaration? Also how do I set the version when writing the output using the XMLOutputter?
2 Answers
The XML Version is parsed and used by the XML parser (SAX). Some parsers support the SAX2 API, and that allows some of the parsers to supply extended parsing information. If the parser does this, the XML version may be available in the Locator2 implementation getXMLVersion(). JDOM does not have a hook on this information, so the data is not yet available in JDOM. It would make a good feature request.
JDOM also outputs data in XML 1.0 version. The differences between 1.0 and 1.1 from JDOM's perspective are slight. The most significant difference is the slightly different handling between different supported characters.
If you want to specify a different XML version for your output you can force the declaration by disabling the XMLOutputter's declaration (setOmitDeclaration() and then dump the declaration yourself on to the stream before outputting the XML.
Alternatively you can extend the XMLOutputProcessor and override the processDelcaration() method to outpuit the declaration you want.
None of these options are easy, and the support for XML 1.1 in JDOM is limited. Your mileage may vary, but please keep me updated on your success, and file issues on the Github issues if you have suggestions/problems: https://github.com/hunterhacker/jdom/issues

- 17,539
- 7
- 42
- 76
I fully believe that rolfl's answer is correct. It isn't the approach I finally took. I decided to just do a quick parsing of the document myself. This probably needs further testing with documents with BOM.
private static Pattern xmlDeclaration = Pattern.compile("<?xml.* version=\"([\\d|\\.]+)\".*?>");
private static boolean isXml10(InputStream inputStream) throws IOException
{
boolean result = true;
InputStreamReader is = null;
BufferedReader br = null;
try
{
is = new InputStreamReader(inputStream);
br = new BufferedReader(is);
String line = br.readLine();
Matcher declarationMatch = xmlDeclaration.matcher(line);
if (declarationMatch.find())
{
String version = declarationMatch.group(1);
result = version.equals("1.0");
}
}
finally
{
is.close();
br.close();
}
return result;
}

- 33
- 1
- 5