How to use xmlSApply with separator?

Asked

Viewed 64 times

2

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

Below is an example for you to 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"

1 answer

1


A 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 separate sub-elements name, price, description and calories. And if by "separator" you mean paste the separate values, you could do then:

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"
  • Thank you so much, Carlos! That’s what I needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.