英文:
xml Unmarshal innerXml and its attributes
问题
我想要解析innerXml及其属性。我编写了一个Unmarshal函数来实现这个功能,但是看起来函数进入了一个无限循环。错误信息如下:
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
示例代码在这里。
我不知道为什么会出现这个问题。有人可以帮助我吗?谢谢。
更新1:感谢Ainar-G。我尝试了他的示例,它可以将innerXml作为chardata获取,这是我没有发现的。如果我将示例更改为这个,结果是空的,它应该包含<c>中的所有原始xml。
更新2:我找到了一个解决方案,但可能有点冗长。代码在这里。
英文:
I want to Unmarshal the innerXml and its attributes. I write a Unmarshal function to implement this, but it looks like the function is in an infinite loop. The error information is
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
The example is here.
I don't know why this happens. Could someone help me, thanks.
Update1: Thanks Ainar-G. I tried his example. It works as get the innerXml as chardata which I did't find. If I change the example as this, the result is empty, it should include all the raw xml in <c>.
Update2: I find a solution, but may be a little wordy. code.
答案1
得分: 2
在你的UnmarshalXML
方法中,你调用了xml.(*Decoder).DecodeElement
,而DecodeElement
又会调用UnmarshalXML
,这样就创建了一个无限循环。你可以创建一个包装结构体,或者在UnmarshalXML
中只解析你结构体的一部分。
**编辑:**如果你想解析节点的所有属性,请参考这个答案中的示例。
工作示例:
func (in *innerXml) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
in.XMLName = start.Name
in.Attrs = make(map[string]string)
for _, attr := range start.Attr {
in.Attrs[attr.Name.Local] = attr.Value
}
err := d.DecodeElement(&in.Value, &start)
if err != nil {
return err
}
return nil
}
在线示例:http://play.golang.org/p/TLcqFSyn94
英文:
In your UnmarshalXML
method you call xml.(*Decoder).DecodeElement
, which in turn calls UnmarshalXML
, etc. This creates the infinite loop. Either create a wrapper struct, or unmarshal only a part of your struct in your UnmarshalXML
.
EDIT: if you want to unmarshal all attributes of a node, see the example in this answer.
Working example:
func (in *innerXml) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
in.XMLName = start.Name
in.Attrs = make(map[string]string)
for _, attr := range start.Attr {
in.Attrs[attr.Name.Local] = attr.Value
}
err := d.DecodeElement(&in.Value, &start)
if err != nil {
return err
}
return nil
}
Playground: http://play.golang.org/p/TLcqFSyn94
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论