xmlrwritexml

use R to read a XML file, select few nodes and write it back to another XML


I am trying to use R to read a XML file, select few nodes and write it back to another XML I am learning now to handle XML files in R, referred the example in this link "http://www.r-bloggers.com/r-and-the-web-for-beginners-part-ii-xml-in-r/", which explains how to read the XML and print selected nodes. I want to extend the example mentioned - I want to select the a range of "plant" nodes (For instance 1 through 5) and store it in anoter XML

The input XML file looks like this

<?xml version="1.0"?>
<CATALOG>
 <PLANT>
  <COMMON>Bloodroot</COMMON>
  <BOTANICAL>Sanguinaria canadensis</BOTANICAL>
  <ZONE>4</ZONE>
  <LIGHT>Mostly Shady</LIGHT>
  <PRICE>$2.44</PRICE>
  <AVAILABILITY>031599</AVAILABILITY>
 </PLANT>
 <PLANT>
  <COMMON>Columbine</COMMON>
  <BOTANICAL>Aquilegia canadensis</BOTANICAL>
  <ZONE>3</ZONE>
  <LIGHT>Mostly Shady</LIGHT>
  <PRICE>$9.37</PRICE>
  <AVAILABILITY>030699</AVAILABILITY>
 </PLANT>
 .
 .
 <CATALOG>

I have the following code

library(XML)
xml.url <- "http://www.w3schools.com/xml/plant_catalog.xml"
xmlfile <- xmlTreeParse(xml.url)
xmltop <- xmlRoot(xmlfile)
saveXML(xmltop[1:5],file="out.xml")

But R gives an error message "Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘saveXML’ for signature ‘"XMLNodeList".
Note: When I try to write the complete XML (using "saveXML(xmlroot,file="out.xml")") it works fine. But only when I try to write the subset it fails.


Solution

  • Try something like

    top <- xmlNode(xmlName(xmltop))
    for(i in 1:5) top <- addChildren(top, xmltop[[i]])
    saveXML(top, file="out.xml")
    file.show("out.xml")
    

    So I created an xmlNode named top and added some children before saving it. I suppose it is not the most elegant way to do that but now it works.

    Hope it helps,

    Alex