首页 > 解决方案 > XML 编码:混合属性和元素

问题描述

我有一个关于编组 Go XML 的问题:我明白了:

<root abc="">
  <element></element>
</root>

但我想要这样:

<root>
  <element abc=""></element>
</root>

(属性abc在子元素中)。

这(很容易)可能吗?

我的代码:

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

type foo struct {
    XMLName xml.Name `xml:"root"`
    Abc     string   `xml:"abc,attr"`
    Element string   `xml:"element"`
}

func main() {
    f := foo{}
    a, err := xml.MarshalIndent(f, "", "  ")
    if err != nil {
        fmt.Println(err)
        os.Exit(0)
    }
    fmt.Println(string(a))
}

标签: xmlgomarshalling

解决方案


您可以定义您的结构,如:

type foo struct {
    XMLName xml.Name `xml:"root"`
    Element struct{
        xml.Name `xml:"element"`
        Abc     string   `xml:"abc,attr"`
    }  
}

推荐阅读