Search code examples
javaxmldomsvgbatik

How to stop xmlns attribute from being created during svg createElement step


I am trying to add a backing box to a Text label in an SVG document. The process is working ok except that the svg.createElement step is also creating an entry in my XML file like this xmlns=""

This entry seems to be causing my SVG file (XML) to not display correctly on my JSVG canvas. If I manually edit the file and remove this entry then the XML displays correctly.

My code snippet is shown below.

    if(domElement instanceof SVGOMTextElement) {
          SVGOMTextElement text = (SVGOMTextElement) domElement;
          NodeList tspans = text.getElementsByTagName("tspan");
          for(int i = 0; i < tspans.getLength(); i++){
             Node node = tspans.item(i);
             SVGOMTSpanElement tspan = (SVGOMTSpanElement) node;
             Element backBox = svg.createElementNS(null,"rect");
             backBox.setAttributeNS(null,"id", "backingRect-attx" + String.valueOf(Math.round(tspan.getExtentOfChar(0).getX())) + "atty" + String.valueOf(Math.round(tspan.getExtentOfChar(0).getY())));
             backBox.setAttributeNS(null,"width", String.valueOf(tspan.getComputedTextLength()));
             backBox.setAttributeNS(null,"height", String.valueOf(tspan.getExtentOfChar(0).getHeight()));
             backBox.setAttributeNS(null,"style", "fill:green;fill-opacity:0.5");
             backBox.setIdAttributeNS(null,"id", Boolean.TRUE);

             text.getParentNode().insertBefore(backBox, text);
    }

The XML tag that this code generates is shown below,

<rect xmlns="" width="59.89038" style="fill:yellow;fill-opacity:0.5"
id="backingRect-attx407atty427" height="16.734436"/>

So the question is how can I stop this attribute (xmlns="") from being added to my SVG XML output file?

I've tried to debug through the code but I cant see an attribute "xmlns" created after the line,

Element backBox = svg.createElementNS(null,"rect");

I was trying to execute a removeAttribute step but this didn't work (as I couldn't find a xmlns attribute).

I am using Apache Batik ver 1.8

Any help would be much appreciated.


Solution

  • The xmlns="" namespace declaration is generated because you chose to put your element in the null namespace.

    Element backBox = svg.createElementNS(null,"rect");
    

    If you create your element in the SVG namespace all should be well.