从xml文件中提取特定字段

时间:2019-08-02 14:46:41

标签: xml go

我有一个XML文件。我需要从该XML文件中提取特定字段并存储在mongo中。如何从下面的XML文件中仅提取名称字段用户?

<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user type="admin">
    <name>Elliot</name>
    <social>
      <facebook>https://facebook.com</facebook>
    </social>
  </user>
  <user type="reader">
    <name>Fraser</name>
    <social>
      <facebook>https://facebook.com</facebook>
    </social>
  </user>
</users>

1 个答案:

答案 0 :(得分:1)

package main

import (
    "encoding/xml"
    "fmt"
)

const data = `<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user type="admin">
    <name>Elliot</name>
    <social>
      <facebook>https://facebook.com</facebook>
    </social>
  </user>
  <user type="reader">
    <name>Fraser</name>
    <social>
      <facebook>https://facebook.com</facebook>
    </social>
  </user>
</users>
`

type Users struct {
    Users []*User `xml:"user"`
}

type User struct {
    Name string `xml:"name"`
}

func main() {
    var users Users
    if err := xml.Unmarshal([]byte(data), &users); err != nil {
        panic(err)
    }
    for _, user := range users.Users {
        fmt.Println(user.Name)
    }
}

https://play.golang.org/p/m65Eio6xskS