【问题标题】:How to process SVG with namespace in R?如何在 R 中使用命名空间处理 SVG?
【发布时间】:2021-07-27 15:37:16
【问题描述】:

我有代码:

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)

当我有这样的 SVG 时:

<?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'>

但它在 SVG 中找不到任何东西。它总是返回 0 个节点,即使我使用 //svg XPath。

如果我删除 xmlns='http://www.w3.org/2000/svg' 它可以正常工作,如何在 XML 中使用默认命名空间并使用 R 处理文件?

【问题讨论】:

    标签: r xml svg


    【解决方案1】:

    我认为问题在于 svg 元素所在的命名空间不同。请看这里:https://www.inflectra.com/support/knowledgebase/kb503.aspx 如何选择这些元素。

    【讨论】:

    • 这看起来像是 XPath 规范或 libxml 库中的错误。看来这行得通xml2::xml_find_all(xml, "//*[name()='text']")
    • @jcubic:你有网址可以更好地理解你的评论吗?我想您的意思是 XPath ".//text" 应该给出与 "//*[name()='text']" 相同的结果。然而,“.//text”以点开头有一个小的区别,表示当前上下文。 "//*[name()='text']" 将从根目录中找到。但老实说,我对R一无所知......
    • 这是一个基本的 XPath,与 R 无关。我认为这是 libxml2 的问题。 R 包只是该库的包装器。我认为.//// 对我来说是一样的。它找到页面上的所有元素,可能是因为我使用根节点作为起点。当我从树中更深的节点开始时,它可能会有所不同。
    猜你喜欢
    • 2011-09-05
    • 2021-08-02
    • 1970-01-01
    • 2014-05-13
    • 2016-06-02
    • 1970-01-01
    • 2012-01-06
    • 2011-05-14
    • 2014-09-19
    相关资源
    最近更新 更多