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:

   1 String parser = XMLResourceDescriptor.getXMLParserClassName();
   2 SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
   3 URI uri; // the URI of your SVG document
   4 Document doc = f.createDocument(uri.toString());

Then you want Batik to build the DOM for you (see BootSvgAndCssDom)

   1 UserAgent      userAgent;
   2 DocumentLoader loader;
   3 BridgeContext  ctx;
   4 GVTBuilder     builder;
   5 GraphicsNode   rootGN;
   7 userAgent = new UserAgentAdapter();
   8 loader    = new DocumentLoader(userAgent);
   9 ctx       = new BridgeContext(userAgent, loader);
  10 ctx.setDynamicState(BridgeContext.DYNAMIC);
  11 builder   = new GVTBuilder();
  12 rootGN    =, doc);

From now on, you can ask for a SVGOMSVGElement from the Document, and you can call for getComputedStyle:

   1 SVGOMSVGElement myRootSVGElement = (SVGOMSVGElement) doc.getDocumentElement();
   3 //I want all the "path" elements for example
   4 NodeList nl = myRootSVGElement.getElementsByTagName("path");
   6 for(int i=0;i<nl.getLength();++i){
   7         Element elt = (Element)nl.item(i);
   9         //I am interested in the "fill" value of the current path element
  10         String fillvalue = myRootSVGElement.getComputedStyle(elt, null).getPropertyValue("fill");
  12         //If I want to parse the "d" attribute
  13         String toParse = elt.getAttribute("d");
  14         //This string can then be fed to a PathParser if you want to create the shapes yourself
  15 }

BuildAndParse (last edited 2012-06-22 14:06:47 by drool)