登录
首页 >  Golang >  Go问答

属性设置 xml 值的方法

来源:stackoverflow

时间:2024-03-07 18:24:25 422浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《属性设置 xml 值的方法》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我相信这应该很容易,但我找不到解决方案。

type data struct {
    itema string `xml:"item-string"`
    itemb item
}

type item struct {
    xmlname   xml.name      `xml:"item-struct"`
    type     string         `xml:"type,attr"`
}

func test() {
    itm := data {
        itema: "good",
        itemb: item {
            type: "nice",
        },
    }
    output, err := xml.marshalindent(&itm,"","    ")
    if err != nil {
        fmt.println(err)
    }
    result := string(output)
    fmt.printf("\n%s\n",result)
}

我得到格式化的 xml 数据:


    good
    

如何设置或添加值到 item-struct,以获得这个:


    good
    very good

正确答案


您可以尝试innerxml标签。

- a field with tag ",innerxml" is written verbatim, not subject
  to the usual marshaling procedure.

更多详情请点击:https://pkg.go.dev/encoding/xml

将代码更改为:

type data struct {
    itema string `xml:"item-string"`
    itemb item
}

type item struct {
    xmlname xml.name `xml:"item-struct"`
    type    string   `xml:"type,attr"`
    value   string   `xml:",innerxml"`
}

func testdata(t *testing.t) {
    itm := data{
        itema: "good",
        itemb: item{
            type:  "nice",
            value: "very good",
        },
    }
    output, err := xml.marshalindent(&itm, "", "    ")
    if err != nil {
        fmt.println(err)
    }
    result := string(output)
    fmt.printf("\n%s\n", result)
}

输出会像这样


    good
    very good

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《属性设置 xml 值的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>