In the project I am working, I need to automatize the creation of an XML document depending on the user input. The part of using the user input to modify the xml document is okay for me but I am new in creating xml documents from scratch in R
I am wondering if an XML document like the one below can be generated in R using the XML or xml2 packages. So far, I have explored the newXMLdoc, xml_new_document and xml_new_root functions but I am not familiar with all the syntax needed to create such an xml file (which should be saved in a local path once finished)
<session>
<modelVersion>1.0.0</modelVersion>
<products>
<product>
<refNo>1</refNo>
<uri>S1A_IW_GRDH_1SDV_20190818T175529_20190818T175554_028627_033D25_22ED.zip</uri>
<productReaderPlugin>class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn</productReaderPlugin>
</product>
<product>
<refNo>2</refNo>
<uri>S2A_MSIL1C_20190823T061631_N0208_R034_T42TXS_20190823T081730.zip</uri>
<productReaderPlugin>class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn</productReaderPlugin>
</product>
</products>
<views/>
</session>
Consider building XML with DOM methods using aforementioned libraries such as XML without the need of concatenating or interpolating strings:
library(XML)
# DATA
df <- data.frame(refNo = c(1, 2),
uri = c('S1A_IW_GRDH_1SDV_20190818T175529_20190818T175554_028627_033D25_22ED.zip',
'S2A_MSIL1C_20190823T061631_N0208_R034_T42TXS_20190823T081730.zip'),
plugin = c('class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn',
'class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn')
)
# CREATE XML FILE
doc = newXMLDoc()
root = newXMLNode("session", doc = doc)
# WRITE XML NODES AND DATA
mvNode = newXMLNode("modelVersion", "1.0.0", parent = root)
for (i in 1:nrow(df)){
prodNode = newXMLNode("products", parent = root)
# APPEND TO PRODUCT NODE
newXMLNode("refNo", df$refNo[i], parent = prodNode)
newXMLNode("uri", df$uri[i], parent = prodNode)
newXMLNode("productReaderPlugin", df$plugin[i], parent = prodNode)
}
vwNode = newXMLNode("views", parent = root)
# OUTPUT XML CONTENT TO CONSOLE
print(doc)
# OUTPUT XML CONTENT TO FILE
saveXML(doc, file="Output.xml")
Output
<?xml version="1.0"?>
<session>
<modelVersion>1.0.0</modelVersion>
<products>
<refNo>1</refNo>
<uri>S1A_IW_GRDH_1SDV_20190818T175529_20190818T175554_028627_033D25_22ED.zip</uri>
<productReaderPlugin>class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn</productReaderPlugin>
</products>
<products>
<refNo>2</refNo>
<uri>S2A_MSIL1C_20190823T061631_N0208_R034_T42TXS_20190823T081730.zip</uri>
<productReaderPlugin>class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn</productReaderPlugin>
</products>
<views/>
</session>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With