用Golang解析XML的代码示例

355 阅读1分钟

多年来,我们一直投入大量的个人时间和精力,与大家分享我们的知识。然而,我们现在需要你的帮助来维持这个博客的运行。你所要做的只是点击网站上的一个广告,否则它将由于托管等费用而不幸被关闭。谢谢你。

在这个例子中,我们将读取一个XML文件并将其映射到其结构类型。最后,为了确认起见,将打印出结果。需要特别注意的是,如果XML内容是 "美化 "的,输出将包含一些特殊字符,如#xA; (换行)、#x9; (制表)和空格。如果是 "最小化",输出结果应该是干净的。

XML文件(经过美化)

<!-- User Bank Account and History -->
<?xml version="1.0" encoding="UTF-8"?>
<user>
    <id>1</id>
	<first_name>John</first_name>
	<middle_name></middle_name>
	<last_name>Doe</last_name>
    <address>Line 1
Line 2

    Line 3
    
Line 4</address>
    <random>
        <nickname>Dummy User</nickname>
        <favourite_colour>Blue</favourite_colour>
    </random>
    <accounts>
        <account number="11" sort_code="111">
            <history>
                <transaction time="2020-09-25T20:41:30+01:00">
                    <operation>Debit</operation>
                    <amount>1021</amount>
                </transaction>
                <transaction time="2019-12-31T00:33:10+01:00">
                    <operation>Credit</operation>
                    <amount>50</amount>
                </transaction>
            </history>
        </account>
        <account number="22" sort_code="222">
            <history>
                <transaction time="2021-03-11T10:11:10+01:00">
                    <operation>Credit</operation>
                    <amount>5000</amount>
                </transaction>
            </history>
        </account>
    </accounts>
</user>

代码

package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"log"
	"os"
)

func main() {
	// Open file
	xmlFile, err := os.Open("input.xml")
	if err != nil {
		log.Fatalln(err)
	}
	defer xmlFile.Close()

	// Read file
	val, err := ioutil.ReadAll(xmlFile)
	if err != nil {
		log.Fatalln(err)
	}

	// Map data
	var user User
	if err := xml.Unmarshal(val, &user); err != nil {
		log.Fatalln(err)
	}

	// Print result (as-is)
	dat, err := xml.MarshalIndent(user, "", "   ")
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(string(dat))
}

type User struct {
	XMLName    xml.Name `xml:"user"`
	Text       string   `xml:",chardata"`
	ID         string   `xml:"id"`
	FirstName  string   `xml:"first_name"`
	MiddleName string   `xml:"middle_name"`
	LastName   string   `xml:"last_name"`
	Address    string   `xml:"address"`
	Random     Random   `xml:"random"`
	Accounts   Accounts `xml:"accounts"`
}

type Random struct {
	Text            string `xml:",chardata"`
	Nickname        string `xml:"nickname"`
	FavouriteColour string `xml:"favourite_colour"`
}

type Accounts struct {
	Accounts []Account `xml:"account"`
}

type Account struct {
	Text     string  `xml:",chardata"`
	Number   string  `xml:"number,attr"`
	SortCode string  `xml:"sort_code,attr"`
	History  History `xml:"history"`
}

type History struct {
	Text        string        `xml:",chardata"`
	Transaction []Transaction `xml:"transaction"`
}

type Transaction struct {
	Text      string `xml:",chardata"`
	Time      string `xml:"time,attr"`
	Operation string `xml:"operation"`
	Amount    string `xml:"amount"`
}