0

After some experimentation, I found the best way (for my code) to convert an r data frame into XML is with the following script:

ConvertDataFrameToXML <- function(dataFrame,fileName) {
  cat("<L><i>", file = fileName, append = TRUE)
  write.table(dataFrame, fileName, append = TRUE, row.names=FALSE, col.names=FALSE, na="",sep="</i><i>",eol="</i></L><L><i>", quote = FALSE)
  cat("</i></L>", file = fileName, append = TRUE)
}

The only problem is that this results in an extra blank row at the end of the table. Is there any way I can open the file and delete the last 6 characters (e.g. as a replacement for the last line of the script)?

Example code:

ConvertDataFrameToXML <- function(dataFrame,fileName) {
  cat("<L><i>", file = fileName, append = TRUE)
  write.table(dataFrame, fileName, append = TRUE, row.names=FALSE, col.names=FALSE, na="",sep="</i><i>",eol="</i></L><L><i>", quote = FALSE)
  cat("</i></L>", file = fileName, append = TRUE)
}

a = data.frame(a= c(1,2,3),b=c(4,5,6))

fileName = "hi.txt"
file.create(fileName, overwrite = TRUE)

cat("<Tables>", file = fileName, append = TRUE)
ConvertDataFrameToXML(a,fileName)
cat("</Tables>", file = fileName, append = TRUE)

print( readChar(fileName, file.info(fileName)$size))

Current output:

<Tables><L><i>1</i><i>4</i></L><L><i>2</i><i>5</i></L><L><i>3</i><i>6</i></L><L><i></i></L></Tables>

Desired output:

<Tables><L><i>1</i><i>4</i></L><L><i>2</i><i>5</i></L><L><i>3</i><i>6</i></L></Tables>
Sinnombre
  • 346
  • 1
  • 7
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 11 '19 at 21:32
  • added example, thanks – Sinnombre Dec 11 '19 at 21:51

1 Answers1

1

The simplest (and so far the only) solution I came up with would be to add this to the end of your ConvertDataFrameToXML function:

string <- readChar(fileName, file.info(fileName)$size)
cat(sub("</i></L><L><i></i></L>", "</i></L>", string), file = fileName)

or this to the end of your entire code:

string <- readChar(fileName, file.info(fileName)$size)
cat(sub("</i></L><L><i></i></L></Tables>", "</i></L></Tables>", string), file = fileName)

Brunox13
  • 775
  • 1
  • 7
  • 21
  • 1
    Yeah this works. In the same vein I could replace the last line with: `string <- readChar(fileName, file.info(fileName)$size) cat(substr(string, 1, nchar(string)-6), file = fileName)` It works, but I was kinda hoping to avoid having the entire file in memory a second time. Oh well, thanks! – Sinnombre Dec 11 '19 at 22:52