从 xml 文件中提取特定字段

我有一个 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>


噜噜哒
浏览 136回答 1
1回答

白衣非少年

package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")const data = `<?xml version="1.0" encoding="UTF-8"?><users>&nbsp; <user type="admin">&nbsp; &nbsp; <name>Elliot</name>&nbsp; &nbsp; <social>&nbsp; &nbsp; &nbsp; <facebook>https://facebook.com</facebook>&nbsp; &nbsp; </social>&nbsp; </user>&nbsp; <user type="reader">&nbsp; &nbsp; <name>Fraser</name>&nbsp; &nbsp; <social>&nbsp; &nbsp; &nbsp; <facebook>https://facebook.com</facebook>&nbsp; &nbsp; </social>&nbsp; </user></users>`type Users struct {&nbsp; &nbsp; Users []*User `xml:"user"`}type User struct {&nbsp; &nbsp; Name string `xml:"name"`}func main() {&nbsp; &nbsp; var users Users&nbsp; &nbsp; if err := xml.Unmarshal([]byte(data), &users); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; for _, user := range users.Users {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(user.Name)&nbsp; &nbsp; }}https://play.golang.org/p/m65Eio6xskS
打开App,查看更多内容
随时随地看视频慕课网APP