xml - Golang XML 解析/解码

标签 xml go

我在 Go 中解析 xml 时遇到问题。谁能帮忙? XML 格式为:

<Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>

    <Ids>
            <Id code='000001' quantity='4' />
            <Id code='000002' quantity='0' />
     </Ids>

</Feed>

最佳答案

对于任何想知道的人,这里有一个示例,它将往返提到的 XML 以进行结构和返回:

func TestXml(t *testing.T) {
    type Id struct {
        Code string `xml:"code,attr"`
        Quantity int `xml:"quantity,attr"`
    }

    type Feed struct {
        Version string `xml:"version,attr"`
        Format string `xml:"format,attr"`
        Date string `xml:"date,attr"`
        Ids []Id `xml:"Ids>Id"`
    }

    x := []byte(`
        <Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>
            <Ids>
                <Id code='000001' quantity='4' />
                <Id code='000002' quantity='0' />
            </Ids>
        </Feed>
    `)

    f := Feed{}
    xml.Unmarshal(x, &f)
    t.Logf("%#v", f)
    t.Log("Code 0:", f.Ids[0].Code)

    b, _ := xml.Marshal(f)
    t.Log(string(b))
}

这会产生以下输出:

xml_test.go:42: domain.Feed{Version:"1.03", Format:"FULL", Date:"2016-04-22T18:31:01.4988282+01:00", Ids:[]domain.Id{domain.Id{Code:"000001", Quantity:4}, domain.Id{Code:"000002", Quantity:0}}}
xml_test.go:43: Code 0: 000001
xml_test.go:46: <Feed version="1.03" format="FULL" date="2016-04-22T18:31:01.4988282+01:00"><Ids><Id code="000001" quantity="4"></Id><Id code="000002" quantity="0"></Id></Ids></Feed>

xml 的文档包含很好的例子。

关于xml - Golang XML 解析/解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825597/

相关文章:

hash - 加密/bcrypt : hashedPassword is not the hash of the given password

pointers - 我如何从golang中的 slice 获取结构指针

python - 从 xml 中删除签名

java - 如何在 Jtree 中刷新 XML

go - 如何使模板与 gin 框架一起工作?

windows - 使用原生 Golang API 在 Windows 上添加图标托盘

go - 如果Go中的字段是 "filtered"是什么意思?

xml - R : XML content does not seem to be XML

c# - 如何在Java中转换C# InnerText XPath方法?

xml - 返回表达式中的XQuery变量未解析其值