I have the text of an SVG image file in a string variable in Groovy. I need to modify it to be formed for embedding as a nested SVG. That means: (1) remove the first line if the first line is an XML declaration that starts as “<?xml”. Or, another way of doing it would be to remove everything up until the start of the SVG tag, i.e., up until “<svg” (2) within the SVG tag check to see if there is a width=“##” or height=“##” attribute. If so, revise the width and height to be 100%.
How can I do this, e.g, using string replacement or xml parser?
I have tried:
def parsedSVG = new XmlParser().parseText(svg)
if (parsedSVG.name() == “xml”) // remove node here
But the problem is that parsedSVG.name() is the svg tag/node, not the xml definition tag. So it still leaves me unable to tell whether the svg starts with the xml tag.
I have also tried the approaches here GPathResult to String without XML declaration But my execution environment does not support XML Node Printer and the InvokeHelper call is giving me errors.
As far as string replacement this is what I have tried. But the regular expression doesn’t seem to work. The log shows svgEnd is basically at the end of the svg file rather than being the end of the svg tag as intended...
String sanitizeSvg(String svg) {
String cleanSvg = svg
def xmlDecStart = svg.indexOf("<?xml")
if (xmlDecStart > -1) {
def xmlDecEnd = svg.indexOf("?>")
cleanSvg = cleanSvg.substring(xmlDecEnd+2)
}
def svgStart = cleanSvg.indexOf("<svg")
logDebug("svgStart is ${svgStart}")
if (svgStart > -1) {
def svgEnd = cleanSvg.indexOf('>', svgStart)
logDebug("svgEnd is ${svgEnd}")
if (svgEnd > -1) {
String svgTag = cleanSvg.substring(svgStart, svgEnd-1)
logDebug("SVG Tag is ${svgTag}")
svgTag = svgTag.replaceAll('width="[^"]*', 'width="100%')
svgTag = svgTag.replaceAll('height="[^"]*', 'height="100%')
logDebug("Changed SVG Tag to ${svgTag}")
cleanSvg.replaceAll('(<svg)([^>]*)',svgTag)
}
}
return cleanSvg
}