【问题标题】:GOlang XML parsing / unmarshalGOlang XML 解析/解组
【发布时间】:2016-08-17 23:02:33
【问题描述】:

我在 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>

【问题讨论】:

  • 你想从中解析出什么?你试过什么?你在哪里卡住了?查看encoding/xml 包以开始使用。
  • 我刚刚设法解决了。我错过了获取 Id 属性的“attr”。

标签: xml go


【解决方案1】:

对于任何想知道的人,这里有一个示例,它将往返提到的 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 的文档包含很好的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多