The xml2 package allows users to create XML documents. I'm trying to create a document using the pipe operator %>%
to add various combinations of child and sibling nodes. I cannot figure out how to create a child node within a child node that is following by the original child's sibling (see example below).
Is it possible to "rise" up a level to then create more nodes or must they be created outside of the chained commands?
What I want
library(xml2)
x1 <- read_xml("<parent><child>1</child><child><grandchild>2</grandchild></child><child>3</child><child>4</child></parent>")
message(x1)
#> <?xml version="1.0" encoding="UTF-8"?>
#> <parent>
#> <child>1</child>
#> <child>
#> <grandchild>2</grandchild>
#> </child>
#> <child>3</child>
#> <child>4</child>
#> </parent>
What I'm creating that's wrong
library(magrittr)
library(xml2)
x2 <- xml_new_document()
x2 %>%
xml_add_child("parent") %>%
xml_add_child("child", 1) %>%
xml_add_sibling("child", 4, .where="after") %>%
xml_add_sibling("child", 3) %>%
xml_add_sibling("child", .where="before") %>%
xml_add_child("grandchild", 2)
message(x2)
#> <?xml version="1.0" encoding="UTF-8"?>
#> <parent>
#> <child>1</child>
#> <child>4</child>
#> <child>
#> <grandchild>2</grandchild>
#> </child>
#> <child>3</child>
#> </parent>
Solution using XML package
This is actually fairly straightforward if done using the XML package.
library(XML)
x2 <- newXMLNode("parent")
invisible(newXMLNode("child", 1, parent=x2))
invisible(newXMLNode("child", newXMLNode("grandchild", 2), parent=x2))
invisible(newXMLNode("child", 3, parent=x2))
invisible(newXMLNode("child", 4, parent=x2))
x2
#> <?xml version="1.0" encoding="UTF-8"?>
#> <parent>
#> <child>1</child>
#> <child>
#> <grandchild>2</grandchild>
#> </child>
#> <child>3</child>
#> <child>4</child>
#> </parent>