Search code examples
rxpathxml2

How to find the xpath associated with a given attribute name in R's xml2 package


I'm using R's xml2 package to manipulate an xml file. I know the name of an attribute and want to find the xpath to it.

I know I can search the xml document for a given node name and return the associated xpath. For example, in the below code I'm searching for the node name 'CHILD_NODE' and returning the xpath.

library(xml2)
library(dplyr)

# Make example data
dat <- read_xml(
  "<PARENT_NODE>
    <CHILD_NODE attr_name='a'>
    </CHILD_NODE>
  </PARENT_NODE>"  
)

# Find xpath to CHILD_NODE:
xpath = dat %>% 
  xml_find_all('//CHILD_NODE') %>% 
  xml_path()
# "/PARENT_NODE/CHILD_NODE"

How can I find the xpath if I instead specify the attribute name? E.g. in the above example I would like to search for the attribute "attr_name" and return the xpath (/PARENT_NODE/CHILD_NODE)?


Solution

  • The proper xpath for that is

    dat %>% 
      xml_find_all('//*[@attr_name]') %>% 
      xml_path()
    

    The * searches all nodes and the @ allows you to specify the attribute you want to fine.