Search code examples
rxml2

add a sibling to a node of xml in R


how to add siblings to a1 and a2 node in R?

input : <a><a1>123</a1> <a2>222</a2> </a>

target <a><a1>123</a1> <a2>222</a2> <a3>222</a3> </a>

library(xml2)
x <- read_xml("<a><a1>123</a1> <a2>222</a2>  </a>"); 
xml_add_sibling(xml_child(x), "<a3>string</a3>"); 
x

Currently, it outpus: <a><a1>123</a1> <<a3>string</a3>/> <a2>222</a2> </a>.

why there are another < and />? Thank you.


Solution

  • You haven't used the function parameters correctly. The second argument in xml_add_sibling is .value, and should be the tag name. Instead of giving the tag the tagname a3, you are giving it the tagname <a3>string</a3>, which is why your extra angle brackets have appeared.

    Simply pass the tagname a3 to the .value argument and enter the contents of the tag in a subsequent unnamed argument as advised in the docs:

    .value       node to insert.

    ...            If named attributes or namespaces to set on the node, if unnamed text to assign to the node.

    library(xml2)
    
    x <- read_xml("<a><a1>123</a1> <a2>222</a2>  </a>")
    xml_add_sibling(xml_child(x), .value = "a3", 'string')
    x
    #> {xml_document}
    #> <a>
    #> [1] <a1>123</a1>
    #> [2] <a3>string</a3>
    #> [3] <a2>222</a2>