How to extract SVG Elements and their styles
This page describes how to extract some elements from a SVG document, and get their styles (or other attributes). The basic idea is to let Batik do all the parsing work, compute the styles (you do not care if the styles are inherited or directly specified), and to ask only for the needed parts.
The first task is to create the document:
String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser); URI uri; // the URI of your SVG document Document doc = f.createDocument(uri.toString());
Then you want Batik to build the DOM for you (see BootSvgAndCssDom)
UserAgent userAgent; DocumentLoader loader; BridgeContext ctx; GVTBuilder builder; GraphicsNode rootGN; userAgent = new UserAgentAdapter(); loader = new DocumentLoader(userAgent); ctx = new BridgeContext(userAgent, loader); ctx.setDynamicState(BridgeContext.DYNAMIC); builder = new GVTBuilder(); rootGN = builder.build(ctx, doc);
From now on, you can ask for a SVGOMSVGElement from the Document, and you can call for getComputedStyle:
SVGOMSVGElement myRootSVGElement = (SVGOMSVGElement) doc.getDocumentElement(); //I want all the "path" elements for example NodeList nl = myRootSVGElement.getElementsByTagName("path"); for(int i=0;i<nl.getLength();++i){ Element elt = (Element)nl.item(i); //I am interested in the "fill" value of the current path element String fillvalue = myRootSVGElement.getComputedStyle(elt, null).getPropertyValue("fill"); //If I want to parse the "d" attribute String toParse = elt.getAttribute("d"); //This string can then be fed to a PathParser if you want to create the shapes yourself }