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

倾然丶 夕夏残阳落幕 提交于 2019-12-13 14:30:31

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/23505906/use-r-to-read-a-xml-file-select-few-nodes-and-write-it-back-to-another-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!