doumaoao0182 2014-01-17 11:03
浏览 40
已采纳

在Go中将通用csv转换为xml

I am trying to convert generic csv files into xml files. The csv file has a header line. The header values represent the element name, and the values in the respective column are the corresponding element values.

My approach so far:

// Read the csv file
file, err := os.Open(*i)
if err != nil {
  log.Fatalf("Error opening input file: %v
", err)
}
defer file.Close()

r := csv.NewReader(file)
r.Comma, _ = utf8.DecodeRuneInString(*s)
lines, err := r.ReadAll()

// header values
header := lines[0]
// Write the xml file
fileOut, err := os.Create(*o)
if err != nil {
  log.Fatalf("Error opening input file: %v
", err)
}
defer fileOut.Close()

for _, l := range lines {
  for i, elem := range l {
    // TODO: Something here is missing...
    xml.EscapeText(fileOut, []byte(header[i]))

    xml.EscapeText(fileOut, []byte(elem))

  }

Question: How do I make it the last part in xml write section work? Or is there a more efficient way of converting csv files into xml files?

  • 写回答

2条回答 默认 最新

  • doudg60800 2014-03-11 12:29
    关注

    The are two solutions: You can reflect the data into a struct,only when you can get the struct , fields and tags. then output XML by methods from xml package. But,if you don't know the struct as I face.there is a stupid but easy way,writing as string, as blow:

    data := XML_HEADER
    data = data + "<records>
    "
    for i := 2; i < len(records); i++ {
     data = data + "  <record "
      for j := 0; j < len(records[i]); j++  {
       data = data + head[j] + `="` + records[i][j] + `" `
                                            }
     data = data + "/>
    "              }
     data = data + "</records>"
     ioutil.WriteFile(xmlFileName, []byte(data), 0644)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab