代码之家  ›  专栏  ›  技术社区  ›  geotheory

用rvest提取xml路径

  •  0
  • geotheory  · 技术社区  · 6 年前

    有人能帮助使用rvest从这个XML中提取路径吗?我可以恢复到字符提取如果没有,但更喜欢rvest。我正在尝试从此页上的svg文件中提取国家形状: https://visionscarto.net/base-maps

    require(rvest)
    require(xml2)
    
    doc = read_xml('https://visionscarto.net/public/fonds-de-cartes-en/visionscarto-airocean.svg')
    
    zim = doc %>% xml_node('.ZWE')
    
    str(zim)
    #> List of 2
    #>  $ node:<externalptr> 
    #>  $ doc :<externalptr> 
    #>  - attr(*, "class")= chr "xml_node"
    
    cat(as.character(zim))
    #> <g class="country ZWE" id="ZWE Zimbabwe" inkscape:groupmode="layer" inkscape:label="ZWE Zimbabwe">
    #>   <path d="M178.84 80.84l.67-.54.16-.54.71-.4.41-.48 1.27-.3.98-.78 1.2.31.5.38.57-.42 1.35-.14 1.34-.14 1.14.2.45-.07 1.53.33-1.28 1.33-.49.3-.3.45.34 1.4.27 1.98-.26.55.36.52-.03 1.17-.58 1.13-.58-.32-.82 1.1-.76.36h-.56l-.58.53-.97.31-1.74-1.41-.75-1.02-1-.9-.56-.13-.71-.8.02-.28-.74-1.14z"/>
    #> </g>
    
    zim %>% xml_node('path')
    #> {xml_missing}
    #> <NA>
    zim %>% xml_attr('d')
    #> [1] NA
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Spacedman    6 年前

    这是可行的,但与XML名称空间一样,我始终不太明白为什么:

    > xml_find_all(doc, "//*[@id='ZWE Zimbabwe']/d1:path") 
    {xml_nodeset (1)}
    [1] <path d="M178.84 80.84l.67-.54.16-.54.71-.4.41-.48 1.27-.3.98-.78 1.2.31. ...
    

    d1

    > xml_ns(doc)
    d1       <-> http://www.w3.org/2000/svg
    inkscape <-> http://www.inkscape.org/namespaces/inkscape
    xlink    <-> http://www.w3.org/1999/xlink