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 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了