'Checking and deleting attributes in SVG using Batik in Java

The question basically says it all. How can I check if SVG has a viewBox attribute? I am using Batik lib. I need this because I need to (at least) notify the user that there is a viewBox attribute.

Can I delete it?



Solution 1:[1]

Using org.w3c.dom classes you'd do something along these lines...

        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
        URL url = new URL(getCodeBase(), "fileName.svg");
        Document doc = f.createDocument(url.toString());

        Element svg = doc.getDocumentElement();

        if (svg.hasAttribute("viewBox")) {
          // notify the user somehow
        }

to delete call

        svg.removeAttribute("viewBox")

Solution 2:[2]

I am using a slightly different approach to the same:

/**
 * Main getViewBoxRect method
 * 
 * Returns the TopLeft point and width and height of the viewBox
 * 
 * @param doc -- the SVGDocument
 * 
 * @return
 */
public static double[] getViewBoxRect(SVGDocument doc)
{
    if (doc == null)
    {
        System.err.printf("\ngetViewBoxRect: null document\n\n");
        return null;
    }
    
    SVGSVGElement el = doc.getRootElement();
    
    if (el == null)
    {
        System.err.printf("\ngetViewBoxRect: null rootElement\n\n");
        return null;
    }

    String viewBoxStr = el.getAttributeNS(null,
            SVGConstants.SVG_VIEW_BOX_ATTRIBUTE);
    
    if (viewBoxStr.length() != 0)
    {
        float[] rect = ViewBox.parseViewBoxAttribute(el, viewBoxStr, null);
        
        return new double[]
        {
                rect[0], rect[1],
                rect[2], rect[3]
        };
    }

    System.err.printf("\ngetViewBoxRect: null viewBox received\n\n");
    return null;
}

Of course, if you get a null value, no viewBox has been set. If you want to reset the viewBox, you can use

doc.removeAttribute("viewBox");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robert Longson
Solution 2 Para Parasolian