R's XML package has an xmlToList function, but does not have the reverse, is there a function for R that will convert a list to an XML object?
I would like something like
listToXML(list('a'))
that returns
<a></a>
but the closest I can find is
library(XML)
xmlNode(list('a'))
which returns
</a>
help on this question, and understanding the conversion of R objects to XML in general appreciated (the XML package appears more focused on the use of R to read XML, with less support for creating XML).
Update... One reason that I could not figure this out is because I did not realize that the trailing '/' in <node/>
indicates an empty node, equivalent to <node></node>
The function newXMLNode
does what you need, i.e., write XML output. See the detailed help and examples in ?newXMLNode
for more details. Here is a short extract:
library(XML)
top = newXMLNode("a")
newXMLNode("b", attrs=c(x=1, y='abc'), parent=top)
newXMLNode("c", "With some text", parent=top)
top
Resulting in:
<a>
<b x="1" y="abc"/>
<c>With some text</c>
</a>
I am surprised that no function already exists for this -- surely there's something already packaged out there.
Regardless, I use the following script to accomplish this:
root <- newXMLNode("root")
li <- list(a = list(aa = 1, ab=2), b=list(ba = 1, bb= 2, bc =3))
listToXML <- function(node, sublist){
for(i in 1:length(sublist)){
child <- newXMLNode(names(sublist)[i], parent=node);
if (typeof(sublist[[i]]) == "list"){
listToXML(child, sublist[[i]])
}
else{
xmlValue(child) <- sublist[[i]]
}
}
}
listToXML(root, li)
You can use the XML::saveXML() function to grab this as a character, if you prefer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With