Megatron
Megatron

Reputation: 17089

How to use xml2 in R to set attribute on node set

I would like to modify all id attributes in my node set using the xml2 package in R.

First, we identify the nodes-of-interest.

library(xml2)

x <- read_xml("<root id='1'><child id ='a' /><child id='b' d='b'/></root>")
nodes <- xml_find_all(x, "//child")  # identify nodes-of-interest

xml_attr(nodes, "id")
#[1] "a" "b"

The correct id attributes have been extracted.

However, when I try to modify these, I get the same value for all nodes.

xml_attr(nodes, "id") <- c("c", "d")
xml_attr(nodes, "id")
#[1] "c" "c"

What I expected was:

#[1] "c" "d"

What is the correct syntax to set up multiple replacements for my node set?

Upvotes: 1

Views: 1241

Answers (1)

neilfws
neilfws

Reputation: 33782

xml_attr() or xml_set_attr() can only set a single attribute, so elements with the same name will get the same value.

xml_attrs or xml_set_attrs() can set multiple attributes, but requires namespaces to distinguish elements with the same name.

One solution: iterate over the list of nodes and the replacement values using purrr::walk2:

library(xml2)
library(purrr)

walk2(nodes, c("c", "d"), ~xml_set_attr(.x, "id", .y))

xml_attr(nodes, "id")
[1] "c" "d"

Upvotes: 1

Related Questions