jcubic
jcubic

Reputation: 66518

How to process SVG with namespace in R?

I have code:

transformXML <- function(xml, fn) {
  x <- xml2::read_xml(xml)
  fn(x)
  tmp <- tempfile(fileext = ".xml")
  xml2::write_xml(x, tmp, options = "format")
  paste(unlist(readLines(tmp)), collapse='\n')
}

fname <- "inst/shiny/test.svg"

svg <- readChar(fname, file.info(fname)$size)

## move text that is in top of the plot tot the left
svg <- transformXML(svg, function(xml) {
    text.nodes <- xml2::xml_find_all(xml, ".//text")
    for (text in text.nodes) {
        if (as.double(xml2::xml_attr(text, 'y')) < 60) {
            xml2::xml_set_attr(text, 'x', '0')
        }
    }
})
message(svg)

When I have SVG like this:

<?xml version='1.0' encoding='UTF-8' ?>
<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 1319.34 500.00'>

But it can't find anything in the SVG. It always returns 0 nodes, even If I use //svg XPath.

If I remove xmlns='http://www.w3.org/2000/svg' it works fine, How can I use default namespace in XML and process the file with R?

Upvotes: 0

Views: 131

Answers (1)

Siebe Jongebloed
Siebe Jongebloed

Reputation: 4869

I suppose the problem is the different namespace the svg elements are in. Take a look here : https://www.inflectra.com/support/knowledgebase/kb503.aspx how to select those elements.

Upvotes: 1

Related Questions