How to use the xmlSApply with separator?

2

I used xmlSApply and would like to get the result with a separator but could not apply.

Below is an example so that they can reproduce:

library(XML)
fileUrl <- "http://www.w3schools.com/xml/simple.xml"
doc <- xmlTreeParse(fileUrl,useInternal=TRUE)
rootNode <- xmlRoot(doc)
xmlName(rootNode)
names(rootNode)

The contents of the first node:

rootNode[[1]]
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food> 

And the result of xmlSApply(rootNode, xmlValue) :

food
"Belgian Waffles$5.95Two of our famous Belgian Waffles with plenty of real maple syrup650"
food 
"Strawberry Belgian Waffles$7.95Light Belgian waffles covered with strawberries and whipped cream900"
food
"Berry-Berry Belgian Waffles$8.95Light Belgian waffles covered with an assortment of fresh berries and whipped cream900" 
food
"French Toast$4.50Thick slices made from our homemade sourdough bread600" 
food
"Homestyle Breakfast$6.95Two eggs, bacon or sausage, toast, and our ever-popular hash browns950"
    
asked by anonymous 20.10.2014 / 16:26

1 answer

1

One way would be:

nos <- lapply(xmlChildren(rootNode), function(x) xmlApply(x, xmlValue))
nos[[1]]
$name
[1] "Belgian Waffles"

$price
[1] "$5.95"

$description
[1] "Two of our famous Belgian Waffles with plenty of real maple syrup"

$calories
[1] "650"

This gives you a list for each food with the subelements separated name , price , description and calories . And if by "separator" you mean paste the separated values, you could do next:

textos <- sapply(nos, function(x) paste(x, collapse=" "))
textos[[1]]
[1] "Belgian Waffles $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup 650"
    
20.10.2014 / 17:40