我有一个基本的xml字段,它看起来像这个<cpe test="123">cpe:/a:openbsd:openssh:5.3p1</cpe>,我想使用Go解除它的编组。我创建了这个对象,当它通常解组和打印test属性时,括号中的内容总是被打印为空的。
package main
import (
"fmt"
"encoding/xml"
)
type Cpe struct {
XMLName xml.Name `xml:"cpe"`
Value string `xml:"chardata"`
Res string `xml:"test,attr"`
}
func main() {
var inputXML = `<cpe test="123">cpe:/a:openbsd:openssh:5.3p1</cpe>`
byteValue := []byte(inputXML)
// Create the onject
var cpe Cpe
// Unmarshal the xml using the Address object
xml.Unmarshal(byteValue, &cpe)
// prints the Res and Address Value
fmt.Println(cpe.Res)
fmt.Println(cpe.Value)
}这些东西的输出是123和nothing。通过搜索,我发现我可以使用innerXML而不是chardata,后者的结果是相同的。
发布于 2020-12-17 10:08:02
chardata是一个选项,而不是XML标记或属性名,因此如果您只需指定一个选项,就必须在它前面加上一个逗号:
Value string `xml:",chardata"`也要检查错误:
// Unmarshal the xml using the Address object
err := xml.Unmarshal(byteValue, &cpe)
fmt.Println("err:", err)
// prints the Res and Address Value
fmt.Println("attribute:", cpe.Res)
fmt.Println("chardata:", cpe.Value)这将输出(在围棋游乐场上尝试它):
err: <nil>
attribute: 123
chardata: cpe:/a:openbsd:openssh:5.3p1https://stackoverflow.com/questions/65338250
复制相似问题