猿问

将结构数组编组为不带父标签的 xml

我正在尝试将带有数组的 go 结构封送到xml中。在这个数组中,我需要为每个元素提供一个属性和一个值。我不需要将其放在父xml标记内。


我有下面的代码。


package main


import (

    "encoding/xml"

    "fmt"

    "os"

)


func main() {

    type Person struct {

        XMLName   xml.Name `xml:"person"`

        Id        int      `xml:"id,attr"`

        FirstName string

    }


    a := &Person{

       Id: 13,

       FirstName: "John",

    }

    b := &Person{

       Id: 14,

       FirstName: "Doe",

    }

    x := []*Person{}

    x = append(x, a)

    x = append(x, b)


    enc := xml.NewEncoder(os.Stdout)

    enc.Indent("  ", "    ")

    if err := enc.Encode(x); err != nil {

        fmt.Printf("error: %v\n", err)

    }

}

它产生以下输出。


<person id="13">

  <FirstName>John</FirstName>

</person>

<person id="14">

  <FirstName>Doe</FirstName>

</person>

但我需要按如下方式进行。


<person id="13">John</person>

<person id="14">Doe</person>

非常感谢对此的任何帮助。我可以用 go 来做这个吗?


ibeautiful
浏览 108回答 1
1回答

九州编程

只需将xml:",chardata"标签添加到FirstName字段即可:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; type Person struct {&nbsp; &nbsp; &nbsp; &nbsp; XMLName&nbsp; &nbsp;xml.Name `xml:"person"`&nbsp; &nbsp; &nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; &nbsp; int&nbsp; &nbsp; &nbsp; `xml:"id,attr"`&nbsp; &nbsp; &nbsp; &nbsp; FirstName string&nbsp; &nbsp;`xml:",chardata"`&nbsp; &nbsp; }&nbsp; &nbsp; a := &Person{&nbsp; &nbsp; &nbsp; &nbsp; ID:&nbsp; &nbsp; &nbsp; &nbsp; 13,&nbsp; &nbsp; &nbsp; &nbsp; FirstName: "John",&nbsp; &nbsp; }&nbsp; &nbsp; b := &Person{&nbsp; &nbsp; &nbsp; &nbsp; ID:&nbsp; &nbsp; &nbsp; &nbsp; 14,&nbsp; &nbsp; &nbsp; &nbsp; FirstName: "Doe",&nbsp; &nbsp; }&nbsp; &nbsp; x := []*Person{}&nbsp; &nbsp; x = append(x, a)&nbsp; &nbsp; x = append(x, b)&nbsp; &nbsp; enc := xml.NewEncoder(os.Stdout)&nbsp; &nbsp; enc.Indent("&nbsp; ", "&nbsp; &nbsp; ")&nbsp; &nbsp; if err := enc.Encode(x); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("error: %v\n", err)&nbsp; &nbsp; }}输出:<person id="13">John</person><person id="14">Doe</person>
随时随地看视频慕课网APP

相关分类

Go
我要回答