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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题