Home > Mobile >  Using xml2 to add child node with an attribute
Using xml2 to add child node with an attribute

Time:10-07

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

CodePudding user response:

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>")
  • Related