Go语言XML解码至TheTag结构体失败,报错元素类型不匹配
Go XML解码问题:无法将嵌套元素解析到结构体
原始XML文档
<DOC> <SubGroup1> <Value1>ABC123</Value1> <Value2>ABC123</Value2> <Value3>ABC123</Value3> <Value4>ABC123</Value4> </SubGroup1> <SubGroup2> <TheTag MyTagAttr="ABC123"> <Value1>ABC123</Value1> <Value2>ABC123</Value2> <Value3>ABC123</Value3> <Value4 MyTagAttr="ABC123">ABC123</Value4> <Value5>ABC123</Value5> <Value6>ABC123</Value6> <Value7>ABC123</Value7> <Value8>ABC123</Value8> <Value9>ABC123</Value9> </TheTag> </SubGroup2> </DOC>
当前使用的Go结构体
type TheTag struct { XMLName xml.Name `xml:"SubGroup2>TheTag"` Value1 string `xml:"Value1"` Value2 string `xml:"Value2"` }
报错信息
error decoding message content: %!w(xml.UnmarshalError=expected element type <SubGroup2>TheTag> but have <DOC>)
问题原因
直接调用xml.Unmarshal将整个XML文档解析到TheTag结构体时,Go XML解析器会期望根元素是<SubGroup2>TheTag,但实际XML的根元素是<DOC>,层级不匹配导致解码失败。
解决方案
方案1:定义完整层级的结构体
对应XML的嵌套结构定义结构体,让解析器匹配整个文档的层级:
import "encoding/xml" type DOC struct { SubGroup2 SubGroup2 `xml:"SubGroup2"` } type SubGroup2 struct { TheTag TheTag `xml:"TheTag"` } type TheTag struct { XMLName xml.Name `xml:"TheTag"` MyTagAttr string `xml:"MyTagAttr,attr"` Value1 string `xml:"Value1"` Value2 string `xml:"Value2"` }
使用时直接解析到DOC结构体,再获取目标实例:
var doc DOC err := xml.Unmarshal(xmlData, &doc) if err != nil { // 处理错误逻辑 } targetTag := doc.SubGroup2.TheTag
方案2:使用xml.Decoder定位目标元素
如果只需提取<TheTag>元素,无需解析整个XML,可以用xml.Decoder遍历元素,找到目标后再解码:
import "encoding/xml" import "strings" func decodeTheTag(xmlData []byte) (*TheTag, error) { decoder := xml.NewDecoder(strings.NewReader(string(xmlData))) var targetTag TheTag for { token, err := decoder.Token() if err != nil { return nil, err } if se, ok := token.(xml.StartElement); ok { // 匹配嵌套层级的目标元素 if se.Name.Local == "TheTag" && se.Parent != nil && se.Parent.Name.Local == "SubGroup2" { if err := decoder.DecodeElement(&targetTag, &se); err != nil { return nil, err } return &targetTag, nil } } } }
说明
方案1适合需要完整解析XML文档的场景,结构清晰易维护;方案2适合仅提取特定嵌套元素的场景,执行效率更高。
内容的提问来源于stack exchange,提问作者jsfelipearaujo
相关产品推荐
相关产品推荐

