GeoTools : XMLEncoder and SLDTransformer

You can encode in XML a style by using the XMLEncoder.

Below is an example on how to perform this task :

// we create a style ; here by reading an already existing sld file
    StyleFactory factory = StyleFactoryFinder.createStyleFactory();
    java.net.URL surl = org.geotools.resources.TestData.getResource(this, "sample.sld");
    SLDStyle stylereader = new SLDStyle(factory,surl);
    Style[] style = stylereader.readXML();

    // we write out our style by using the XMLEncoder
    StringWriter output = new StringWriter();
    // or: Writer output = new PrintWriter(System.out);
    XMLEncoder encode = new XMLEncoder(output, style[0]);

 

Nevertheless it is the old fashion mode to export styles as XML ; the normal way nowadays is to use the SLDTransformer as following :

// we create a style ; here by reading an already existing sld file
    StyleFactory factory = StyleFactoryFinder.createStyleFactory();
    java.net.URL surl = org.geotools.resources.TestData.getResource(this, "sample.sld");
    SLDParser stylereader = null; //We use SLDParser instead of SLDStyle
    try {
        stylereader = new SLDParser(factory, aUrl);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Style[] style = stylereader.readXML();

    SLDTransformer aTransformer = new SLDTransformer();
    aTransformer.setIndentation(4);
    aTransformer.transform(style[0], new PrintWriter(System.out));

 

Alternatively, one can also export a complete StyledLayerDescriptor object as XML :

// we create a default SLD (let the user add to it) and then spit out the XML
    StyleFactory factory = StyleFactoryFinder.createStyleFactory();
    StyledLayerDescriptor sld = factory.createStyledLayerDescriptor();
    ...
    SLDTransformer aTransformer = new SLDTransformer();
    aTransformer.setIndentation(4);
    String xml = aTransformer.transform(sld);