douchui1488 2012-09-13 03:14
浏览 12
已采纳

进行XML编组和根元素

In Go, you can marshall a struct to XML, e.g.:

package main

import (
    "encoding/xml"
    "fmt"
    )

type person struct {
    Name string
    Starsign string
}

func main() {
    p := &person{"John Smith", "Capricorn"}
    b,_ := xml.MarshalIndent(p,"","   ")
    fmt.Println(string(b))
}

produces output:

<person>
   <Name>John Smith</Name>
   <Starsign>Capricorn</Starsign>
</person>

My problem is, the person type is lower-case "p" because I want that to be private to the package. But I'd prefer the XML element to be uppercase: <Person>. The fields within the struct can be marshalled to other names using tags (e.g. `xml:"name"`) against the structure fields but this doesn't seem to be an option for the structure type.

I have a work-around using templates, but it would be nice to know a better answer.

  • 写回答

2条回答 默认 最新

  • dongzhi5846 2012-09-13 04:02
    关注

    According to the encoding/xml.Marshal documentation:

    The name for the XML elements is taken from, in order of preference:

    • the tag on the XMLName field, if the data is a struct
    • the value of the XMLName field of type xml.Name
    • the tag of the struct field used to obtain the data
    • the name of the struct field used to obtain the data
    • the name of the marshalled type

    You can use a tag on the XMLName field in the struct to override the person struct's XML tag name. In order to avoid putting it in your actual person struct, you can create an anonymous struct that embeds the person struct you are marshaling.

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    type person struct {
        Name        string
        Starsign    string
    }
    
    func marshalPerson(p person) ([]byte, error) {
        tmp := struct {
            person
            XMLName struct{}    `xml:"Person"`
        }{person: p}
    
        return xml.MarshalIndent(tmp, "", "   ")
    }
    
    func main() {
        p := person{"John Smith", "Capricorn"}
        b, _ := marshalPerson(p)
        fmt.Println(string(b))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'