0

Is there a build-in way to parse an SLD file with geotools, which works for SLD 1.0.0 and SLD 1.1.0?

gillesB
  • 1,061
  • 1
  • 14
  • 30

1 Answers1

1

I have not found a build-in way, but one possible solution is to retrieve the SLD version from the XML file. Depending on the version it can be parsed with the suitable Configuration class.

public  Style createStyleFromSld(String uri) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document xmlDocument = db.parse(uri);

  XPath xPath = XPathFactory.newInstance().newXPath();
  String version = xPath.compile("/StyledLayerDescriptor/@version").evaluate(xmlDocument);
  Configuration sldConf;
  if (version != null && version.startsWith("1.1")) {
    sldConf = new org.geotools.sld.v1_1.SLDConfiguration();
  } else {
    sldConf = new org.geotools.sld.SLDConfiguration();
  }
  StyledLayerDescriptor sld = (StyledLayerDescriptor) new DOMParser(sldConf, xmlDocument).parse();    
  NamedLayer l = (NamedLayer) sld.getStyledLayers()[0];
  Style style = l.getStyles()[0];
  return style;
}
gillesB
  • 1,061
  • 1
  • 14
  • 30
  • 1
    In an ideal world you could look at the mime type of the file and use that to distinguish them, but failing that either your approach or trying one then the other is the best plan – Ian Turton Sep 27 '19 at 09:31