Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using xml2 to add child node with an attribute

Tags:

r

xml2

I'm using R's xml2 package to edit an XML document. I'd like to add a node with a specific XML attribute, but I don't seem to understand the syntax of add_child_node.

Adding a node works great:

library(xml2)
my_xml <- read_xml("<fruits><apple/><banana/></fruits>")
xml_add_child(.x = my_xml, .value = "coconut")
my_xml

# {xml_document}
# <fruits>
# [1] <apple/>
# [2] <banana/>
# [3] <coconut/>

and according my understanding of the documentation, I should be able to add an attribute to the node by using the ellipsis argument to provide a named vector of text:

my_xml <- read_xml("<fruits><apple/><banana/></fruits>")
xml_add_child(.x = my_xml, .value = "coconut", c(id="new"))
my_xml

# {xml_document}
# <fruits>
# [1] <apple/>
# [2] <banana/>
# [3] <coconut>new</coconut>

However, this appears to simply insert the text into the node, as it does when the text is unnamed. The attribute doesn't show up at all.

What I'd like to get is this:

# {xml_document}
# <fruits>
# [1] <apple/>
# [2] <banana/>
# [3] <coconut id="new"/>

Any thoughts? I'm aware that I can set attributes manually after the fact using xml_attr<- but my use case doesn't support that method very well.

Snapshot of the documentation for anyone who doesn't want to pull it up: Documentation from ?xml2::add_child_node

like image 700
Dubukay Avatar asked Feb 26 '26 14:02

Dubukay


1 Answers

Just remove the c()

xml_add_child(.x = my_xml, .value = "coconut", id = "new")

-output

> my_xml
{xml_document}
<fruits>
[1] <apple/>
[2] <banana/>
[3] <coconut id="new"/>

data

my_xml <- read_xml("<fruits><apple/><banana/></fruits>")
like image 146
akrun Avatar answered Mar 01 '26 03:03

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!