Search code examples
javaxmlxsddtdproperties-file

Use XSD schema to describe Java Properties generated by 'storeToXML '


I use Properties#storeToXML to convert java.util.Properties to XML format. However, by default it generates XML with DTD schema for it:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    ...
</properties>

Is it possible to use XSD schema for it instead? How can I reconfigure it?


Solution

  • Using the default classes, there seems to be no way of changing a doctype declaration to a XSD-based approach.

    But there seems to be a plugin way of interventing into the XML storing behavior (at least in Java 8): The method Properties.storeToXml internally delegates to a loaded XmlPropertiesProvider (from package sun.util.spi).

    This properties provider is either loaded by inspecting the system property "sun.util.spi.XmlPropertiesProvider" or (if not found) by loading it with the service loader mechanism.

    With this approach you can implement a XmlPropertiesProvider yourself (it's an abstract class with the methods load and store) and do those XML parts in your own way.


    Since at least May, 2016, the Properties class uses jdk.internal.util.xml.PropertiesDefaultHandler and the following hard-coded object instantiation to both store and load XML:

    PropertiesDefaultHandler handler = new PropertiesDefaultHandler();
    

    This means the following code will no longer work to set the default handler for XML-based properties:

    System.setProperty(
        "sun.util.spi.XmlPropertiesProvider",
        XmlPropertiesTransformer.class.getCanonicalName()
    );
    

    There does not appear to be a way to introduce a different handler because the PropertiesDefaultHandler class does not permit injection of custom handlers.