英文:
How to marshal multiline to XML in Go?
问题
我需要将坐标存储到KML文件中。应该像这样:
<coordinates>
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
</coordinates>
如果我将字符串连接起来并尝试作为一个字符串进行编组,每个新行都会得到&#xA
。
KmlLineString 结构体 {
Coordinates string `xml:"coordinates"`
}
如果我将其更改为Coordinates []string`xml:"coordinates"`
,每一行都会有标签。
我该如何做到这一点?
英文:
I need to store coordinates to KML file. It should be like this:
<coordinates>
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
</coordinates>
If I join the string and try to marshal as one string I get &#xA
for every new line
KmlLineString struct {
Coordinates string `xml:"coordinates"`
}
If I change it to Coordinates []string`xml:"coordinates"`
I get tags on every line.
How can I do this?
答案1
得分: 3
如@icza在他的评论中指出的那样,&#xA;
是一个转义的换行符,在编组XML时是正确的输出。任何有效的XML解码器都能够解组它并理解它表示的内容。
如果你想要输出字面的换行符,也许是为了使XML更易读,那么你可以使用,innerxml
标签选项。这个选项指示编码器按原样编组内容。然而,正如@icza在另一个评论中指出的那样,如果被标记为,innerxml
的字段包含无效的XML,编组这样的字段的结果也将是无效的XML。
例如:
var xml_data = `<coordinates>
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
</coordinates>`
type KmlLineString struct {
Coordinates string `xml:",innerxml"`
}
https://go.dev/play/p/kXOjZZ-DyHc
或者
var xml_data = `
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
`
type KmlLineString struct {
Coordinates Coordinates `xml:"coordinates"`
}
type Coordinates struct {
Value string `xml:",innerxml"`
}
https://go.dev/play/p/kiN-NUt67ny
英文:
As @icza points out in his comment, the &#xA;
is an escaped new line and is the correct output when marshaling XML. Any valid XML decoder will be able to unmarshal that and understand what it represents.
If you want to output the literal new lines regardless, perhaps to make the XML human-friendly, then you can use the ,innerxml
tag option. This option instructs the encoder to marshal the content verbatim. However, as @icza points out in another comment, if the field that's tagged with ,innerxml
contains invalid XML, the result of marshaling such a field will also be invalid XML.
For example:
var xml_data = `<coordinates>
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
</coordinates>`
type KmlLineString struct {
Coordinates string `xml:",innerxml"`
}
https://go.dev/play/p/kXOjZZ-DyHc
Or
var xml_data = `
51.600223,25.003058,0
51.600223,25.003065,0
51.600213,25.003065,0
51.600212,25.003065,0
51.600217,25.003075,0
`
type KmlLineString struct {
Coordinates Coordinates `xml:"coordinates"`
}
type Coordinates struct {
Value string `xml:",innerxml"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论