Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create xml from R objects, e.g., is there a 'listToXml' function?

Tags:

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>

like image 686
David LeBauer Avatar asked Jun 06 '11 17:06

David LeBauer


2 Answers

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> 
like image 135
Andrie Avatar answered Oct 11 '22 21:10

Andrie


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.

like image 26
Jeff Allen Avatar answered Oct 11 '22 21:10

Jeff Allen