gpt4 book ai didi

xml - GOLang XML 无法使用 xml.MarshalIndent 在一个标记中创建值和属性

转载 作者:IT王子 更新时间:2023-10-29 01:23:55 26 4
gpt4 key购买 nike

Go 的新手,必须使用“encoding/xml”包中的 xml.MarshalIndent 创建 xml 文件。一个要求是像这样创建一个标签:

`

   <Attributes>
<Attribute name="Me">I really like this GO lang</Attribute>
<Attribute name="problem">the xml package is not behaving</Attribute>
</Attributes>

`

一组带有值和属性的标签,但无论我做什么(我尝试了很多不同的方法),我就是无法让它工作。

我编写的代码生成了这个:`

<Attributes>
<Attribute Name="J3K Solutions">
<Attribute>IT Support</Attribute>
</Attribute>
<Attribute Name="stakoverflow">
<Attribute>The place I go for help</Attribute>
</Attribute>
</Attributes>

`

但是我需要它看起来像这样:`

<Attributes>
<Attribute Name="J3K Solutions" >IT Support</Attribute>
<Attribute Name="stakoverflow" >The place I go for help</Attribute>
</Attributes>

`我一直在阅读文档,并试图让它工作几个小时。有人知道这是否可行吗?

代码:

 package main

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

type attributes struct {
Name string `xml:",attr"`
Attribute string `xml:"Attribute"`
}

type fXML struct {
MessageID string `xml:"MessageID,attr"`
Timestamp string `xml:"timestamp,attr"`
Version string `xml:"version,attr"`
Header struct {
From struct {
Credential struct {
Domain string `xml:"domain,attr"`
Identity string `xml:"Identity"`
} `xml:"Credential"`
} `xml:"From"`
To struct {
Credential struct {
Domain string `xml:"domain,attr"`
Identity string `xml:"Identity"`
} `xml:"Credential"`
} `xml:"To"`
Attributes struct {
Attribute []attributes
}
} `xml:"Header"`
}

func main() {

rdata := &fXML{}
t := time.Now()
rdata.MessageID = "I'm really liken this GO language!"
rdata.Timestamp = t.Format("2006-01-02T15:04:05")
rdata.Version = "1.0"
rdata.Header.From.Credential.Domain = "j3ksolutions.com"
rdata.Header.From.Credential.Identity = "J3K Solutions"
rdata.Header.To.Credential.Domain = "stackoverflow.com"
rdata.Header.To.Credential.Identity = "stackoverflow"
rdata.Header.Attributes.Attribute = append(rdata.Header.Attributes.Attribute,
attributes{
Name: "J3K Solutions",
Attribute: "IT Support and Custom Programing",
})
rdata.Header.Attributes.Attribute = append(rdata.Header.Attributes.Attribute,
attributes{
Name: "stakoverflow",
Attribute: "The place I go for help",
})

if m, err2 := xml.MarshalIndent(rdata, "", "\t"); err2 != nil {
panic("xml.MarshalIndent FAILED: " + err2.Error())
} else {
xmlheader := fmt.Sprintf("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n")
m = append([]byte(xmlheader), m...)
fmt.Printf("\n%s\n\n", m)
}
}

最佳答案

您可能需要使用“,chardata”结构标签来写入字符数据。这是doc

  • a field with tag ",chardata" is written as character data, not as an XML element.

您可以按如下方式定义结构

type attributes struct {
XMLName xml.Name `xml:Attribute"`
Name string `xml:",attr"`
Attribute string `xml:",chardata"`
}

这是播放链接:go play

关于xml - GOLang XML 无法使用 xml.MarshalIndent 在一个标记中创建值和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com